2014-07-03 67 views
-2
$.post(loginurl, {username: $username, password: $password}, function(response) { 

      if (response.session_id === null) { 
       // alert("Please enter correct credentials!"); 
       return; 
      } 

寫了這個,但沒有得到我任何結果:

//POST 


     WebClient clt = new WebClient(); 
      var JsonLoginString = JsonConvert.SerializeObject(credentials); 

      clt.Headers["Content-Type"] = "application/json"; 


      string check = "username:"+username+"password:"+password; 


      clt.UploadStringAsync(new Uri(Config.loginurl), check); 
      clt.UploadStringCompleted += clt_UploadStringCompleted; 
    private void clt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
     { 

     } 

編輯:

我嘗試使用這樣的:

public void Login(string username, string password) 
    { 
     var request = (HttpWebRequest)WebRequest.Create(Config.loginurl); 
     request.ContentType = "application/json"; 
     request.Method = "POST"; 
     request.BeginGetRequestStream(new AsyncCallback(GetRequestCallBack), request); 



    } 

    private void GetRequestCallBack(IAsyncResult ar) 
    { 
     string username = "[email protected]"; 
     string password = "admin"; 
     HttpWebRequest request = (HttpWebRequest)ar.AsyncState; 
     Stream postStream = request.EndGetRequestStream(ar); 
     Byte[] byteData = Encoding.UTF8.GetBytes("username:"+username+"password:"+password); 
     postStream.Write(byteData, 0, byteData.Length); 
     postStream.Close(); 

     request.BeginGetResponse(new AsyncCallback(GetResponseCallBack), request); 

    } 
    string recMessage = ""; 
    private void GetResponseCallBack(IAsyncResult ar) 
    { 
     HttpWebRequest request = (HttpWebRequest)ar.AsyncState; 
     using (var response = request.EndGetResponse(ar)) 
     using (var reader = new StreamReader(response.GetResponseStream())) 
     { 
      Deployment.Current.Dispatcher.BeginInvoke(() => 
      { 
       SendData(); 
      }); 
      recMessage = reader.ReadToEnd(); 
     } 

    } 

    private void SendData() 
    { 
     MessageBox.Show(recMessage.ToString()); 
    } 
+0

感謝您的提問。我已經編輯它以刪除「移動」部分。這只是「Windows Phone」。 「Windows Mobile」是之前的電話;) –

+0

查看httpclient後的例子。 – loop

+0

http://stackoverflow.com/questions/16695018/how-to-post-to-restful-api-with-windows-phone-8?lq=1和噸的其他問題+谷歌MSDN HttpClient –

回答

1

HttpClient可以幫助你。 This is the Nuget package

using (var client = new HttpClient()) 
{ 
    client.BaseAddress = new Uri("http://www.url.com/"); 
    client.Content = new StringContent(jsonEncodedCredentials, Encoding.UTF8, "application/json")) 

    HttpResponseMessage response = await client.PostAsync("api/login"); 
    if (response.IsSuccessStatusCode) 
    { 
     string jsonEncodedReponse = await response.Content.ReadAsStringAsync(); 
     //Do something with the response 

    } 
} 
+0

什麼通過BaseAddress?如果您的登錄地址與「http://www.mydomain.com/api/login」類似,BaseAddress是「http://www.mydomain.com/」和「api/login」,我已編輯我的問題 – vini

+0

是資源 –