2016-11-08 242 views
0

我正在編寫UWP應用程序。POST請求UWP

我需要使用JSON發送POST請求到服務器

這裏是我的下載JSON和寫入值碼:

public async void AllOrders_down() 
    { 


     string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders"; 

     var json = await FetchAsync(url); 


     List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json); 

     OrdersList = new List<RootObject>(rootObjectData); 


    } 
    public async Task<string> FetchAsync(string url) 
    { 
     string jsonString; 

     using (var httpClient = new System.Net.Http.HttpClient()) 
     { 
      var stream = await httpClient.GetStreamAsync(url); 
      StreamReader reader = new StreamReader(stream); 
      jsonString = reader.ReadToEnd(); 
     } 

     return jsonString; 
    } 

我需要如何與此JSON服務器發送POST請求?

感謝您的幫助。

回答

1

您應該使用httpClient.PostAsync()

+0

好吧,但我需要編寫代碼,從這個'var json = await FetchAsync(url);'並通過POST請求發送json? – Eugene

+0

這樣的事情? (var client = new HttpClient()) var content = new StringContent(json,Encoding.UTF8,「application/json」); var result = client.PostAsync(url,content).Result; }' – Eugene

+1

更好地爲'async/await'方法調用'var result = await client.PostAsync(url,content);'。 – toadflakz

2

以下是我在UWP應用程序中使用的Post請求示例。

using (HttpClient httpClient = new HttpClient()) 
{ 
    httpClient.BaseAddress = new Uri(@"http://test.com/"); 
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8")); 

    string endpoint = @"/api/testendpoint"; 

    try 
    { 
     HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json"); 
     HttpResponseMessage response = await httpClient.PostAsync(endpoint, content); 

     if (response.IsSuccessStatusCode) 
     { 
      string jsonResponse = await response.Content.ReadAsStringAsync(); 
      //do something with json response here 
     } 
    } 
    catch (Exception) 
    { 
     //Could not connect to server 
     //Use more specific exception handling, this is just an example 
    } 
} 
+0

我嘗試你的代碼。 後端dev說他看到空行,但沒有收到數據。 – Eugene

+0

有趣。您收到了您嘗試訪問的端點的200響應? –

+0

是的。 我想我知道問題在哪裏。 我下載json並將其寫入'var json' async。 當我設置斷點時,我看到'json'值= null。 – Eugene