2014-11-14 54 views
2

我正在使用Windows Phone 8應用程序。我必須執行登錄過程,並且我會發送一些數據。我通過谷歌瀏覽器的POSTMAN使用了服務的網址。到現在爲止還挺好。我嘗試了提琴手,雖然登錄憑證很好,但我從服務器「無效請求」得到了答案,因爲我沒有設置Content-type:「application/json」。做完這一切後,所有的工作。在我的C#代碼中,我再次得到了來自服務器的完整mu證書的未預期答案。我相信我沒有正確設置內容類型。貝婁是我的代碼:我想通過post方法調用服務器,但無法正常工作

public void UserAuthMethod(UserAuthMethod userAuth) 
     { 
      var request = (HttpWebRequest)WebRequest.Create("http://startaxi.punct.ro/api/init/userAuth"); 
      request.ContentType = "application/json"; 
      request.Headers[0] = "application/json"; //I tried to add this line but no results 
      var postData = JsonConvert.SerializeObject(userAuth); 
      var data = Encoding.Unicode.GetBytes(postData); 

      request.Method = "POST"; 
      request.ContentLength = data.Length; 

      var responseString = request.BeginGetResponse(GetResponseCallback, request); 
     } 

void GetResponseCallback(IAsyncResult result) 
     { 
      HttpWebRequest request = result.AsyncState as HttpWebRequest; 
      if (request != null) 
      { 
       try 
       { 
        WebResponse response = request.EndGetResponse(result); 
        var reader = new StreamReader(response.GetResponseStream()); 
        string result2 = reader.ReadToEnd(); 

       } 
       catch (WebException e) 
       { 
        return; 
       } 
      } 
     } 

我的代碼有什麼問題?任何幫助將不勝感激! 預先感謝您:)

+1

添加報頭應該是這樣'.Headers.Add( 「內容類型」, 「應用/ JSON」)'。你應該像以前那樣使用'.ContentType'來完成它。我想這裏的問題是,你只是設置'.ContentLength',不寫任何真正的數據到請求流。因此它沒有內容數據。 – user887675

+0

您只是將數據長度分配給請求,而不是數據本身。我還沒有想到我的早晨咖啡,所以我可能錯過了一些東西! –

+0

user887675:標題沒有添加方法 –

回答

1

瞧答案:

public void UserAuthMethod(UserAuthMethod userAuth) 
     { 
      WebClient webclient = new WebClient(); 
      Uri uristring = null; 
      uristring = new Uri("http://startaxi.punct.ro/api/init/userAuth",UriKind.Absolute);//Please replace your URL here 
      webclient.Headers["Content-type"] = "application/json"; 
      //content 
      Dictionary<string, string> toSerialize = new Dictionary<string, string>(); 
      toSerialize.Add("email", userAuth.Email); 
      toSerialize.Add("password", userAuth.Password); 
      string JsonStringParams = JsonConvert.SerializeObject(toSerialize); 

      webclient.UploadStringCompleted += wc_UploadStringCompleted; 
      webclient.UploadStringAsync(uristring, "POST", JsonStringParams); 
     } 

     private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
     { 
      //try 
      { 

       if (e.Result != null) 
       { 
        string responce = e.Result.ToString(); 
        //To Do Your functionality 
       } 
      } 
      // catch 
      { 
      } 
     } 
相關問題