如何在正文中发送包含字符串数组的发布请求

时间:2015-10-13 14:00:01

标签: c# .net webrequest

我正在尝试在控制台应用中发送带有数组的http发布请求,如果正文中有字符串,但它无效。

以下是代码:

WebRequest request = WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string[] firstData = { "89", "354", "AF001" };
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(firstData);
requestWriter.Close();

string[] secondData = { "8911", "354", "01" };;
StreamWriter requestWriter2 = new StreamWriter(request.GetRequestStream());
requestWriter2.Write(secondData);
requestWriter2.Close();

2 个答案:

答案 0 :(得分:1)

您无法重复使用相同的 n max.iterations (both/loop1/loop2) 10^1..10^2 11 2 11 10^2..10^3 20 3 20 10^3..10^4 42 5 42 10^4..10^5 94 11 94 10^5..10^6 196 23 196 up to 10^7 379 43 379 up to 10^8 722 83 722 up to 10^9 1269 157 1269 流,这是您在WebRequest个实例上调用request.GetRequestStream时所做的。这就是它抛出异常的原因。我不确定为什么你要两次获取请求流,每次都是另一个StreamWriter。您可以简单地将它们组合成一个:

StreamWriter

作为旁注,您可以使用WebRequest request = WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream())) { string[] firstData = { "89", "354", "AF001" }; requestWriter.Write(firstData); string[] secondData = { "8911", "354", "01" }; ; requestWriter.Write(secondData); } 极大地降低代码的语法:

WebClient

答案 1 :(得分:0)

我将string[]更改为var并且有效:

 WebRequest request = WebRequest.Create(apiUrl);
 request.Method = "POST";
 request.ContentType = "application/json;charset=UTF-8";

 data = "[ \"89\", \"354\", \"AF001\" ]";

 StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());

 requestWriter.Write(data);

 requestWriter.Close();



  WebResponse response = request.GetResponse();
  Console.WriteLine(((HttpWebResponse)response).StatusDescription);

  response.Close();

  request = WebRequest.Create(url);
  request.Method = "POST";
  request.ContentType = "application/json;charset=UTF-8";


   StreamWriter requestWriter2 = new StreamWriter(request.GetRequestStream())

   var data2 = ""[ \"55\", \"3524\", \"b01\" ]";

   requestWriter2.Write(data2);
   requestWriter2.Close();

   WebResponse response2 = request.GetResponse()
   Console.WriteLine(((HttpWebResponse)response2).StatusDescription);

为第二个请求创建了新的WebResponse和StreamWriter