2014-06-24 53 views
0

我想要訪問我的WP8應用程序的特定Web服務器的一些其他服務,我不能做得很好。例如,這是我嘗試登錄用戶時使用的代碼。我必須傳遞一個代表Json object(「參數」)的字符串與用戶名和密碼,並且響應也是一個json對象。我找不到在休息請求中通過這個pasameters的方式。 這是代碼;在Windows Phone 8使用C#中的REST請求的問題

public void login(string user, string passwrd) 
{ 

    mLoginData.setUserName(user); 
    mLoginData.setPasswd(passwrd); 

    string serviceURL = mBaseURL + "/service/user/login/"; 

    string parameters = "{\"username\":\"" + mLoginData.getUserName() + "\",\"password\":\"" + mLoginData.getPasswd() + "\"}"; 
    //MessageBox.Show(parameters); 
    //MessageBox.Show(serviceURL); 
    //build the REST request 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL); 
    request.ContentType = "application/json"; 
    request.Method = "POST"; 
    //async request launchs "Gotresponse(...) when it has finished. 
    request.BeginGetResponse(new AsyncCallback(GotResponse), request); 

} 


private void GotResponse(IAsyncResult ar) 
{ 
    try 
    { 
     string data; 
     // State of request is asynchronous 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)ar.AsyncState; 
     using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar)) 
     { 
      // Read the response into a Stream object. 
      Stream responseStream = response.GetResponseStream(); 
      using (var reader = new StreamReader(responseStream)) 
      { 
       data = reader.ReadToEnd(); 
      } 
      responseStream.Close(); 
     } 
    } 
    catch (Exception e) 
    { 
     string exception = e.ToString(); 
     throw; 
    } 
} 

我與webClienthttpClient類試圖太過,但沒有任何結果。 謝謝並對我的英語不好。

回答

0

我用HttpClient類解決了它。這是代碼。

public async void login(string user, string passwrd) 
{ 


    string serviceURL = ""; 
    string parameters = ""; 

    HttpClient restClient = new HttpClient(); 
    restClient.BaseAddress = new Uri(mBaseURL); 
    restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, serviceURL); 
    req.Content = new StringContent(parameters, Encoding.UTF8, "application/json"); 
    HttpResponseMessage response = null; 
    string responseBodyAsText = ""; 
    try 
    { 
     response = await restClient.SendAsync(req); 
     response.EnsureSuccessStatusCode(); 

     responseBodyAsText = await response.Content.ReadAsStringAsync(); 
    } 
    catch (HttpRequestException e) 
    { 
     string ex = e.Message; 
    } 
    if (response.IsSuccessStatusCode==true) 
    { 
     dynamic data = JObject.Parse(responseBodyAsText); 

    } 
    else 
    { 
     if (response.StatusCode == HttpStatusCode.Unauthorized) 
     { 
      MessageBox.Show("User or password were incorrect"); 
     } 
     else 
     { 
      MessageBox.Show("NNetwork connection error"); 
     } 
    } 
} 

我沒有正確設置請求的標頭值。 我希望這可以幫助某人。

相關問題