对于以下代码,我得到以下错误,
System.Net.ProtocolViolationException:您必须提供一个请求正文
如果您设置ContentLength> 0或SendChunked == true。通过致电做到这一点
[Begin] GetResponse之前的[Begin] GetRequestStream。
我不确定为什么会引发此错误,任何评论或建议都将有所帮助
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);
}
}
最佳答案
该错误很可能是由于您混合了异步操作和同步操作而导致的。 HttpWebRequest.BeginGetRequestStream的文档说:
您的应用程序不能为特定请求混合同步和异步方法。如果调用BeginGetRequestStream方法,则必须使用BeginGetResponse方法来检索响应。
您的代码调用BeginGetRequestStream
,但是调用GetResponse
。
我认为正在发生的事情是它调用了BeginGetRequestStream
,这开始异步写入请求流,但是在主线程上它同时调用了GetResponse
。因此,它正在尝试在格式化请求之前发出请求。
研究链接的MSDN主题中的示例,并相应地修改您的代码。
关于c# - System.Net.ProtocolViolationException异常C#发布和获取响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18192423/