我通过以下代码发送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();
}
我不知道为什么!我花了更多时间找出解决方案,例如set proxy = null,...但没有结果。 有没有办法忽略这一行。我不需要接收响应数据。我试过通过以下方式替换这些行:
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Flush();
responseStream.Close();
}
但我无法正确发送邮件请求。请帮我。非常感谢!
答案 0 :(得分:0)
如果你根本不关心响应或它是否失败,你可以在新线程上排队响应并忽略它。
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);
}
});