C# 如何在发送Post请求时忽略来自的响应数据?
我通过以下代码发送邮寄请求:C# 如何在发送Post请求时忽略来自的响应数据?,c#,.net,httpwebrequest,streamreader,httpwebresponse,C#,.net,Httpwebrequest,Streamreader,Httpwebresponse,我通过以下代码发送邮寄请求: try { string responseContent; request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookieContainer; // Set Method to "POST"
try
{
string responseContent;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
// Set Method to "POST"
request.Method = "POST";
// Set the content type of the WebRequest
request.ContentType = "application/x-www-form-urlencoded";
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
// Set the content length
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(requestCommand);
request.ContentLength = byteArray.Length;
// Get the request stream
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (BufferedStream buffer = new BufferedStream(responseStream))
{
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
}
}
}
return responseContent;
}
catch (Exception ex)
{
return ex.Message;
}
}
很好用。但是下面的代码行太慢了
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
我不知道为什么!我花了更多的时间来寻找解决方案,比如设置proxy=null,。。。但没有结果。
有什么办法可以忽略这一行吗。我不需要接收响应数据。我已尝试将该行替换为:
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Flush();
responseStream.Close();
}
但我无法正确且成功地发送Post请求。请帮帮我。非常感谢 如果您根本不关心响应或它是否失败,您可能可以在新线程上排队等待响应并忽略它
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
// now put the get response code in a new thread and immediately return
ThreadPool.QueueUserWorkItem((x) =>
{
using (var objResponse = (HttpWebResponse) request.GetResponse())
{
responseStream = new MemoryStream();
objResponse.GetResponseStream().CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);
}
});