如何在HttpWebRequest中使用MultipartFormDataContent?

时间:2016-04-13 15:55:16

标签: c# forms httpwebrequest multipartform-data httpwebresponse

我目前正在尝试将包含多个文件的表单提交到目标服务器,但不知道如何使用HttpWebRequest发送此表单数据。表单的类型为MultipartFormDataContent。到目前为止,我已经看到了使用HttpWebRequest提交表单的方法,但这是通过将表单构造为字符串然后将其转换为字节数组来完成的。所以像这样,

string postData = "";

        foreach (string key in postParameters.Keys)
        {
            postData += HttpUtility.UrlEncode(key) + "="
                  + HttpUtility.UrlEncode(postParameters[key]) + "&";
        }

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        myHttpWebRequest.Method = "POST";

        byte[] data = Encoding.ASCII.GetBytes(postData);
Stream requestStream = myHttpWebRequest.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();

但是,我的表单不是字符串,而是MultipartFormDataContent类型,所以我不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

所以我在这里做的第一件事就是将MultipartFormDataContent对象转换为Byte数组。

Byte [] byteArray = await form.ReadAsByteArrayAsync();

然后我将它传递给一个函数,它生成HttpWebRequest()。

    private string HttpPostRequest(string url, MultipartFormDataContent formData, Byte[] form)
    {
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        myHttpWebRequest.Method = "POST";

        myHttpWebRequest.ContentType = formData.Headers.ContentType.ToString();
        myHttpWebRequest.ContentLength = formData.Headers.ContentLength.Value;
        myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
        myHttpWebRequest.ServicePoint.ConnectionLimit = 24;
        myHttpWebRequest.KeepAlive = false;
        myHttpWebRequest.Timeout = System.Threading.Timeout.Infinite;
        myHttpWebRequest.AllowWriteStreamBuffering = false;
        System.Net.ServicePointManager.Expect100Continue = false;


        Stream requestStream = myHttpWebRequest.GetRequestStream();
        int i = 0;
        attachAttempt:
        try
        {
            requestStream.Write(form, 0, form.Length);
        }
        catch (IOException e) 
        {
            if (i < 5)
            {
                i++;
                goto attachAttempt;
            }

            DialogResult attachFail;
            string attachFailMessage = e.Message.ToString() + " Please check your network and try again.";
            string attachFailCaption = "Network error.";
            MessageBoxButtons emailFailButtons = MessageBoxButtons.OK;
            attachFail = MessageBox.Show(attachFailMessage, attachFailCaption, emailFailButtons, MessageBoxIcon.Error);

            return ""; 
        }
        requestStream.Close();

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();

        myHttpWebResponse.Close();

        return pageContent;
    }

在研究了与该领域相关的几个建议之后,我编译了这个。您可能会发现您可能不需要在myHttpWebRequest对象上设置一些标志,但这对我有用。我还发现网络上的问题会严重影响这一点,因为主机和目标机器之间的连接可能会中止,因此我将Write()放入try和catch块以防万一我需要输出错误。