以下のコードでは、次のエラーが発生しています。
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);
}
}