C# 模擬HTTP表單提交參數並附帶附件

/// 模擬HTTP表單提交參數並附帶附件
/// </summary>
/// <param name="fileName">文件完整路徑或相對路徑</param>
/// <param name="url">HTTP鏈接地址</param>
/// <param name="keys">參數名稱</param>
/// <param name="values">參數值</param>
/// <returns>請求返回值</returns>
public static string SubmitData(string fileName, string url, string[] keys, string[] values)
{
    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";

    StringBuilder sb = new StringBuilder();

    if (keys != null)
    {
        for (int i = 0; i < keys.Length; i++)
        {
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"" + keys[i] + "\"\r\n\r\n");
            sb.Append(values[i]);
            sb.Append("\r\n");
        }
    }


    sb.Append("--");
    sb.Append(boundary);
    sb.Append("\r\n");
    sb.Append("Content-Disposition: form-data; name=\"NUM_FILE\"; filename=\"");
    sb.Append(Path.GetFileName(fileName));
    sb.Append("\"");
    sb.Append("\r\n");
    sb.Append("Content-Type: application/octet-stream");
    sb.Append("\r\n");
    sb.Append("\r\n");

    string postHeader = sb.ToString();
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

    byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
    httpWebRequest.ContentLength = length;

    Stream requestStream = httpWebRequest.GetRequestStream();
    requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

    byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        requestStream.Write(buffer, 0, bytesRead);
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

    HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string returnValue = "";
    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("GB2312")))
    {
        returnValue = reader.ReadToEnd();
    }
    webResponse.Close();
    requestStream.Close();
    fileStream.Close();
    return returnValue;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章