用于发送POST请求,可以发送各种POST参数、传送文件,返回结果、下载文件。
说明如下:
public static string HttpPost(
OnHttpPostProgress onProgress, //上传或下载进度,不需要可以传NULL
string url, // 请求的URL地址
Dictionary<string,string> post = null, //要发送的参数,可以发送键值对、数组、对象等复杂数据
string toFile = null, //如果指定了一个路径,请求结果保存为文件,如果传NULL,直接返回查询结果
string upFile = null, //要上传的文件,传NULL不上传文件
string fileField=null //默认为upFile,即PHP接收时使用$_FILE['upFile']
);
public static class HttpWeb
{
/// <summary>
/// HTTP 进度事件
/// </summary>
/// <param name="bUpload">TRUE为上传进度,FALSE为下载进度</param>
/// <param name="lFininsh">已完成大小</param>
/// <param name="lTotal">总共大小</param>
public delegate void OnHttpPostProgress(bool bUpload, long lFininsh, long lTotal);
/// <summary>
/// 发送Post请求
/// </summary>
/// <param name="onProgres">上传或下载进度改变时</param>
/// <param name="url">URL地址</param>
/// <param name="post">键值对,如果要发送数组,请参考:"man[0][name]"=>"hexu"; "man[0][age]", "18"); "man[1][name]"=>"hexu"; "man[1][age]", "18");如果不发送数据,可以传NULL</param>
/// <param name="toFile">结果保存至文件,如果为NULL,则直接返回结果</param>
/// <param name="file">要发送的文件路径</param>
/// <param name="fileField">文件上传字段名字</param>
/// <returns></returns>
public static string HttpPost(OnHttpPostProgress onProgress, string url, Dictionary<string, string> post = null, string toFile = null, string upFile = null, string fileField = null)
{
string result = null;
try
{
//FileStream ws = null;
string boundary = "------------" + DateTime.Now.Ticks.ToString();
byte[] tailBoundary = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
hwr.Method = "POST";
hwr.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
hwr.Proxy = null;
hwr.ProtocolVersion = HttpVersion.Version10;
hwr.KeepAlive = true;
hwr.Timeout = -1;
hwr.ReadWriteTimeout = -1;
hwr.AllowWriteStreamBuffering = false;
long fileSize = 0;
StringBuilder sb = new StringBuilder();
if (post != null)
{
bool bFirst = true;
foreach (var pam in post)
{
if (bFirst)
bFirst = false;
else
sb.Append("\r\n");
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pam.Key);
sb.Append("\"\r\n\r\n");
sb.Append(pam.Value);
}
}
if (!string.IsNullOrWhiteSpace(upFile))
{
FileInfo fi = new FileInfo(upFile);
if (!fi.Exists)
throw new Exception("File Not Found");
fileSize = fi.Length;
fi = null;
if (fileField == null)
fileField = "upFile";
if ( post != null && post.Count > 0)
sb.Append("\r\n");
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileField);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(upFile));
sb.Append("\"\r\n");
string expName = Path.GetExtension(upFile);
if ((string.Compare(expName, ".xls", true) == 0) || (string.Compare(expName, ".xlsx", true) == 0))
sb.Append("Content-Type: application/vnd.ms-excel");
else
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n\r\n");
}
byte[] partOne = Encoding.UTF8.GetBytes(sb.ToString());
long totalSize = partOne.Length + fileSize + tailBoundary.Length;
long progressSize = 0;
hwr.ContentLength = totalSize;
using (Stream pstStream = hwr.GetRequestStream())
{
DateTime dtLastInvoke = DateTime.MinValue;
pstStream.Write(partOne, 0, partOne.Length);
progressSize += partOne.LongLength;
if (onProgress != null)
{
dtLastInvoke = DateTime.Now;
onProgress.BeginInvoke(true, progressSize, totalSize, null, null);
}
if (fileSize > 0)
{
using (FileStream fs = new FileStream(upFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] buffers = new byte[4096];
int size = br.Read(buffers, 0, 4096);
while (size > 0)
{
pstStream.Write(buffers, 0, size);
progressSize += size;
if (onProgress != null)
{
DateTime dtNow = DateTime.Now;
if (dtNow.Subtract(dtLastInvoke).TotalMilliseconds >= 500)
{
dtLastInvoke = dtNow;
onProgress.BeginInvoke(true, progressSize, totalSize, null, null);
}
}
size = br.Read(buffers, 0, 4096);
}
br.Close();
}
fs.Close();
}
}
pstStream.Write(tailBoundary, 0, tailBoundary.Length);
pstStream.Flush();
pstStream.Close();
if (onProgress != null)
onProgress.BeginInvoke(true, progressSize, totalSize, null, null);
}
using (HttpWebResponse response = hwr.GetResponse() as HttpWebResponse)
{
totalSize = response.ContentLength;
progressSize = 0;
DateTime dtLastInvoke = DateTime.Now;
using (Stream resStream = response.GetResponseStream())
{
if (string.IsNullOrWhiteSpace(toFile))
{
using (StreamReader sr = new StreamReader(resStream))
{
StringBuilder sbr = new StringBuilder();
char[] buff = new char[1024];
int size = sr.Read(buff, 0, 1024);
while (size > 0)
{
for (int i = 0; i < size; ++i)
sbr.Append(buff[i]);
progressSize += size;
if (onProgress != null)
{
DateTime dtNow = DateTime.Now;
if (dtNow.Subtract(dtLastInvoke).TotalMilliseconds >= 500)
{
dtLastInvoke = dtNow;
onProgress.BeginInvoke(false, progressSize, totalSize, null, null);
}
}
size = sr.Read(buff, 0, 1024);
}
sr.Close();
result = sbr.ToString();
}
}
else
{
using (BinaryReader sr = new BinaryReader(resStream))
{
using (FileStream ws = new FileStream(toFile, FileMode.Create, FileAccess.ReadWrite))
{
int size = 0;
byte[] buff = new byte[1024];
size = sr.Read(buff, 0, 1024);
while (size > 0)
{
ws.Write(buff, 0, size);
progressSize += size;
if (onProgress != null)
{
DateTime dtNow = DateTime.Now;
if (dtNow.Subtract(dtLastInvoke).TotalMilliseconds >= 500)
{
dtLastInvoke = dtNow;
onProgress.BeginInvoke(false, progressSize, totalSize, null, null);
}
}
size = sr.Read(buff, 0, 1024);
}
ws.Close();
}
sr.Close();
result = "success";
}
}
}
}
if (onProgress != null)
{
onProgress.BeginInvoke(false, progressSize, totalSize, null, null);
}
}
catch (Exception e)
{
result = e.Message;
}
return result;
}
}