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", "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()的做用是將參數進行編碼。cookie

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

將返回的數據寫入文件app

//寫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;  
}

(萬)ide

相關文章
相關標籤/搜索