HttpWebRequest POST,已经确定服务器接受到文件,但获取响应内容的时候一直卡住不动,得不到服务器的响应(已确定服务器能够正常响应),为什么在request.GetResponse() 卡住不动?
///
/// 上传文件请求
///
/// <param name="url">Url</param>
/// <param name="filePath">文件路径</param>
/// <param name="formDatas">表单数据(字典格式)</param>
public string UploadRequest(string url, string filePath, Dictionary<string, string> formDatas)
{
// 时间戳,用做boundary
string timeStamp = DateTime.Now.Ticks.ToString("x");
//根据uri创建HttpWebRequest对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
request.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
request.Timeout = 10000; //设置获得响应的超时时间(10秒)
request.ContentType = "multipart/form-data; boundary=" + timeStamp;
//表单信息
string boundary = "--" + timeStamp;
string form = "";
string formFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
string formEnd = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type:application/octet-stream\r\n\r\n";
foreach (var pair in formDatas)
{
form += string.Format(formFormat, pair.Key, pair.Value);
}
form += string.Format(formEnd, "file", Path.GetFileName(filePath));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(form);
//读取file文件
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] fileArray = binaryReader.ReadBytes((int)fileStream.Length);
//结束边界
byte[] boundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + timeStamp + "--\r\n");
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
request.ContentLength = length; //请求内容长度
//返回信息
string result = "";
try
{
Stream postStream = request.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
//文件内容
postStream.Write(fileArray, 0, fileArray.Length);
//添加尾部边界
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close();
//获取响应内容
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
{
result = reader.ReadToEnd();
}
response.Close();
responseStream.Close();
return result;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
fileStream.Close();
binaryReader.Close();
}
}