WebClient以POST方式发送Web请求

本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求 Cookies前后一致。其中application/x-www-form-urlencoded会告诉服务器该参数是以param1=value1& amp;param2=value2&param3=value3方式拼接的。

private bool postDataandDownloadFile(string fileName)
{
string url = "http://www.huiyaosoft.com/test.aspx";
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}&", "username", "admin");
postData.AppendFormat("{0}={1}&", "password", "");
postData.AppendFormat("{0}={1}&", "nickname", UrlEncode("辉耀"));
try
{
if (wc == null)
wc = new System.Net.WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); // 继承Cookies
if (!string.IsNullOrEmpty(cookies))
wc.Headers.Add("Cookie", cookies); // Upload the input string using the HTTP 1.0 POST method.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
// 此处返回的是一个文件
byte[] byteResult = wc.UploadData(url, "POST", byteArray);
// 取得Cookies
cookies = wc.ResponseHeaders["Set-Cookie"]; if (type == || type == )
writeFile(byteResult, fileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}

由于设置了"Content-Type"为"application/x-www-form-urlencoded",所以postData必须先进行urlencode。UrlEncode()的作用是将参数进行编码。

public string UrlEncode(string str)
{
byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
return System.Web.HttpUtility.UrlEncode(byStr);
}

将返回的数据写入文件

//写byte[]到fileName
private bool writeFile(byte[] pReadByte, string fileName)
{
FileStream pFileStream = null;
try
{
pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
pFileStream.Write(pReadByte, , pReadByte.Length);
}
catch
{
return false;
}
finally
{
if (pFileStream != null)
pFileStream.Close();
}
return true;
}

(万)

上一篇:Spring整合Struts2的方法


下一篇:SpringBoot集成Spring Security入门体验