2017-09-21 105 views
0

我試圖發送一個請求到在線API接收網絡數據,它是succesfull與正常的鍵值,但沒有與數組的價值,我無法找到它在互聯網上沒有創造大量額外的課程。發佈數組值到JSON API與C#

這是我試圖張貼到普通數據的網址(第3個需要一個數組而不是單個對象)。

IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>() 
     { 
       new KeyValuePair<string, string>("keyA","ValueA"), 
       new KeyValuePair<string, string>("keyB", ""), 
       new KeyValuePair<string, string>("KeyC", "ValueCDE"), //array 
     }; 
     HttpContent q = new FormUrlEncodedContent(queries); 
     Console.WriteLine(q.ToString()); 
     using (HttpClient client = new HttpClient()) 
     { 
      using (HttpResponseMessage response = await client.PostAsync(url, q)) 
      { 
       using (HttpContent content = response.Content) 
       { 
        string mycontent = await content.ReadAsStringAsync(); 
        HttpContentHeaders headers = content.Headers; 
        Console.WriteLine(mycontent); 
        Console.WriteLine(response); 
       } 
      } 
     } 

我試圖發送原始數據到網址,但我沒有收到它的迴應。

async static void PostRawRequest(string url) 
    { 
     string rawr = @"{ 
     ""a"":""a"", 
     ""b"":"""", 
     ""c"": [""C"", ""D"",""F""], 
     ""StickerColor"": ""red"" 
     }"; 

     string result = ""; 
     using (var client = new WebClient()) 
     { 
      client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
      result = client.UploadString(url, "POST", rawr); 
     } 
     Console.WriteLine(result); 

}

誰能幫助我的第一(發送數組值)或第二(發送原始數據)?

+0

,而不是試圖手動創建一個字符串,只需使用[Json.NET(https://www.newtonsoft.com/json) –

+0

您應該放棄WebClient。它已被替換爲HttpClient,順便說一句,也可以序列化對象到Json –

回答

1

如果可以,請使用庫來爲您處理序列化。然後,你可以做這樣的事情(使用Newtonsoft.Json):

using (var client = new HttpClient()) 
{ 
    var json = JsonConvert.SerializeObject(yourObject); 
    client.PostAsync(yourUri, new StringContent(json, Encoding.UTF8, "application/json")); 
}