2016-04-26 50 views
0

IT非常令人沮喪,在一個星期後,我無法解決將JSON內容發佈到Web服務器API的簡單問題。我想我會放棄使用Xamarin的這種嘗試。爲什麼PostAsJsonAsync的參數不作爲JSON內容包含在帖子中?

我想在Xamarin應用中使用PostAsJsonAsync發佈JSON參數。程序確實會發佈該網站,但參數不會被編碼爲JSON內容。有誰知道爲什麼?

public async void Login() 
{ 
    var formcontent = new FormUrlEncodedContent(new[] 
    { 
     new KeyValuePair<string,string>("email","[email protected]"), 
     new KeyValuePair<string, string>("password","Xy345") 
    }); 
    var FlyVIPAPI = new HttpClient(); 
    var request = await FlyVIPAPI.PostAsJsonAsync("http://www.ik.com.br/app/api/LoginUser.php", formcontent); 
    var response = await request.Content.ReadAsStringAsync(); 
    //var res = JsonConvert.DeserializeObject(response); 
    var RepostaJson = Newtonsoft.Json.Linq.JObject.Parse(response); 
    System.Diagnostics.Debug.WriteLine(RepostaJson["success"]); 
    System.Diagnostics.Debug.WriteLine(RepostaJson["error"]); 
    return; 
} 

回答

0
public class LoginRequest 
{ 
    public string email { get; set; } 
    public string password { get; set; } 
} 

public async void Login() 
{ 
    using (var FlyVIPAPI = new HttpClient()) 
    { 
     // Create Request object 
     var requestObj = new LoginRequest { email = "[email protected]", password = "Xy345" }; 

     // Serialize to JSON string 
     var formcontent = JsonConvert.SerializeObject(requestObj); 

     // Create HTTP content 
     var content = new StringContent(formcontent, Encoding.UTF8, "application/json"); 

     // POST Request 
     var request = await FlyVIPAPI.PostAsync("http://www.ik.com.br/app/api/LoginUser.php", content); 

     // Read Response 
     var response = await request.Content.ReadAsStringAsync(); 

     .... 
    } 
} 

此外,我建議在using聲明包裝你HttpClient從而將被處理掉,一旦您的代碼塊完成。釋放資源。

+0

感謝您的及時迴應。 – user3358125

+0

我用你的建議替換我的代碼,結果是一樣的。該郵件正在發送沒有JSON編碼參數 – user3358125

+0

@ user3358125我想我誤解了你的問題,你想要做一個帶有url參數不正文內容的POST嗎? – Plac3Hold3r

相關問題