2017-09-21 70 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")); 
}