【发布时间】:2013-08-12 16:49:07
【问题描述】:
对于下面的代码,我收到以下错误,
System.Net.ProtocolViolationException:您必须提供请求正文 如果您设置 ContentLength>0 或 SendChunked==true。通过调用来做到这一点 [Begin]GetRequestStream 在 [Begin]GetResponse 之前。
我不确定为什么会抛出此错误,任何 cmets 或建议都会有所帮助
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://");
// Set the ContentType property.
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
request.KeepAlive = true;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Start the asynchronous operation.
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
Console.ReadLine();
// Close the stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
response.Close();
private static void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation.
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
allDone.Set();
}
现在我修改了使用 HttpClient 的代码,但不起作用,
public static async void PostAsync(String postData)
{
try
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync("http://", new StringContent(postData));
Console.WriteLine(response);
//response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
【问题讨论】:
-
你正在通过休眠直到它完成来打败异步的目的。您应该使您的代码实际上是异步的。考虑使用
Tasks。 -
更好的是,切换到
HttpClient。 -
如何设置“postData”变量?在 ReadCallBack 方法中?
-
我在调用 POST Http 请求之前设置 postData 变量的值