WebClient以POST方式发送Web请求

来源:互联网 发布:php获取数组元素个数 编辑:程序博客网 时间:2024/06/07 18:04

本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求Cookies前后一致。其中application/x-www-form-urlencoded会告诉服务器该参数是以param1=value1&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", "123456");    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 == 1 || type == 3)            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, 0, pReadByte.Length);    }    catch    {        return false;    }    finally    {        if (pFileStream != null)            pFileStream.Close();    }    return true;}

(完)

0 0
原创粉丝点击