带边界的 C# HTTP POST

标签 c# httpwebrequest http-post

我需要一些帮助来使用 C# 设置 HTTP Post。感谢我提前收到的任何帮助。

这里使用 Fiddler 是我的 RAW POST:

POST http://www.domain.com/tester.aspx HTTP/1.1
User-Agent: Tegan
Content-Type: multipart/form-data; boundary=myboundary
Host: www.domain.com
Content-Length: 1538
Expect: 100-continue


<some-xml>

        <customer>
                <user-id>george</user-id>
                <first-name>George</first-name>
                <last-name>Jones</last-name>
        </customer>

</some-xml>

我的要求有点棘手。他们需要一个有边界的多部分帖子。我不熟悉设置边界。如果有人可以提供帮助,我将不胜感激。

这是我的要求:

POST http://www.domain.com/tester.aspx HTTP/1.0(CRLF)
User-Agent: myprogramname(CRLF)
Content-Type: multipart/form-data; boundary=myboundary(CRLF)
Content-Length: nnn(CRLF)
(CRLF)
(CRLF)
--myboundary(CRLF)
Content-Disposition: form-data; name=”xmlrequest”(CRLF)
Content-Type: text/xml(CRLF)
(CRLF)
(XML request message)(CRLF)
(CRLF)
--myboundary--(CRLF)

所以我认为 POST 应该是这样的,但我需要一些 C# 方面的帮助。

POST http://www.domain.com/tester.aspx HTTP/1.1
User-Agent: Tegan
Content-Type: multipart/form-data; boundary=myboundary
Content-Length: 1538

--myboundary
Content-Disposition: form-data; name="xmlrequest"
Content-Type: text/xml

<some-xml>

            <customer>
                    <user-id>george</user-id>
                    <first-name>George</first-name>
                    <last-name>Jones</last-name>
            </customer>

    </some-xml>

(CRLF)
--myboundary--

这是我用来创建 WebRequest 的 C# 代码。

HttpWebRequest request = null;
Uri uri = new Uri("http://domain.com/tester.aspx");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.UserAgent = "NPPD";
request.ContentType = "multipart/form-data; boundary=myboundary";
request.ContentLength = postData.Length;


using (Stream writeStream = request.GetRequestStream())
{
    writeStream.Write(postData, 0, postData.Length);
}
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
        {
            result = readStream.ReadToEnd();
        }
    }
}
return result;

最佳答案

我写了一篇关于此的博客,并提供了一个可用于发送 multipart/form-data 请求的示例方法。在这里结帐:http://www.bratched.com/en/home/dotnet/69-uploading-multiple-files-with-c.html

关于带边界的 C# HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091208/

相关文章:

c# - Twitter API : 401 on POST, GET 工作正常

java - Android - 如何处理异步 Http 崩溃

ios - AF 网络 2.0 : is it possible to put pure json in the body of a POST request?

c# - 通过c#获取多个格式错误的cookie

c# - 如何向 ASP.NET MVC web 应用程序发出授权的 HttpWebRequest

android - 如何从 Android 发送 http post 请求?

c# - 捕获 C# winform 应用程序中的所有异常

c# - C#将列动态添加到数据库中的表

c# - 使用 Stream CopyTo 时跳过字节顺序标记 (BOM)

c# - 在 VBScript 中使用 DLL