C# http httpwebrequest getresponse 无响应问题
使用form-data进行post,
之前用变各种方法,
System.GC.Collect();
webRequest.KeepAlive = false;
webRequest.UseDefaultCredentials = true;
getresponse都报异常,直到加上
webRequest.ServicePoint.Expect100Continue = false;//important
应该是服务器设置问题
System.GC.Collect();
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("meetId", meetID);
parameters.Add("stateType", e_stateType.ToString());
parameters.Add("data", paramData);
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(Url));
webRequest.Method = "POST";
webRequest.KeepAlive = false;
webRequest.UseDefaultCredentials = true;
webRequest.ServicePoint.Expect100Continue = false;//important
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
// 开始边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// 结束结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
var newLineBytes = Encoding.UTF8.GetBytes("\r\n");
using (var stream = new MemoryStream())
{
// 写入开始边界符
stream.Write(beginBoundary, 0, beginBoundary.Length);
// 写入字符串
var keyValue = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
foreach (string key in parameters.Keys)
{
string temp = string.Format(keyValue, key, parameters[key]);
var keyValueBytes = Encoding.UTF8.GetBytes(string.Format(keyValue, key, parameters[key]));
stream.Write(beginBoundary, 0, beginBoundary.Length);
stream.Write(keyValueBytes, 0, keyValueBytes.Length);
}
// 写入结束边界符
stream.Write(endBoundary, 0, endBoundary.Length);
webRequest.ContentLength = stream.Length;
stream.Position = 0;
var tempBuffer = new byte[stream.Length];
stream.Read(tempBuffer, 0, tempBuffer.Length);
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
using (var newresponse = webRequest.GetResponse())
using (StreamReader httpStreamReader = new StreamReader(newresponse.GetResponseStream(), Encoding.UTF8))
{
string result = httpStreamReader.ReadToEnd();
}
}
}
webRequest.Abort();
本文介绍了一种在C#中使用HttpWebRequest进行POST请求时遇到无响应问题的解决方案,通过设置webRequest.ServicePoint.Expect100Continue为false解决了服务器响应延迟的问题,并详细展示了如何使用form-data进行数据传输。

2387

被折叠的 条评论
为什么被折叠?



