将MultiPart / Form-Data作为Web请求时出现问题

时间:2014-09-04 13:47:31

标签: c# xml multipartform-data webrequest

我有一个HTML POST请求,我需要在c#

中复制

HTML就像

<FORM action="http://RemoteServerURL" enctype="multipart/form-data" method=POST>
    <TEXTAREA id="TextAreaXML" name="xmlmsg" rows="20" cols="100">   </TEXTAREA>
    <button type="submit">Send</button>
</form>

TextArea期待一个inout,如下所示

<?xml version="1.0" encoding="utf-8"?>
<OnlineCheck>
  <Header>
    <BuyerAccountId>XXXXXX</BuyerAccountId>
    <AuthCode>XXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX</AuthCode>
    <Type>STOCK</Type>
  </Header>
  <Item line="1">
    <ManufacturerItemIdentifier />
    <DistributorItemIdentifier>3109750</DistributorItemIdentifier>
    <Quantity>7</Quantity>
  </Item>
</OnlineCheck>

本部分工作正常。

现在我尝试在c#中复制它,如下所示。

WebRequest req = WebRequest.Create("http://RemoteServerURL");
string xmlmsg = "<?xml version=" + '"' + "1.0" + '"' + " encoding==" + '"' + "utf-8" + '"' + "?><OnlineCheck><Header><BuyerAccountId>XXXXXX</BuyerAccountId><AuthCode>XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX</AuthCode><Type>STOCK</Type></Header><Item line=" + '"' + "1" + '"' + "><ManufacturerItemIdentifier /><DistributorItemIdentifier>3109750</DistributorItemIdentifier><Quantity>7</Quantity></Item></OnlineCheck>";

byte[] send = Encoding.Default.GetBytes(xmlmsg);
req.Method = "POST";
req.ContentType = "multipart/form-data";
req.ContentLength = send.Length;

Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();

WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();

这失败了,我收到了消息

  

“请求被拒绝,因为没有找到多部分边界XML   请求“

。所以我知道对服务器的请求正在运行。但输入或出现问题。请帮忙

3 个答案:

答案 0 :(得分:0)

摆脱sout.Flush();,没有必要。

答案 1 :(得分:0)

似乎错误信息是清楚的,它要求多部分边界。 内容类型:multipart / mixed;边界=&#34;边界&#34;

What is the boundary parameter in an HTTP multi-part (POST) Request?

答案 2 :(得分:0)

我知道这是一个老话题,但是我想与社区分享我的解决方案,因为上周我遇到了类似的问题,因此提出了多方要求。我不能使用RestSharp,因为它不支持除表单数据以外的内容类型,我需要“相关”。我还需要基于带有json元数据的pdf的base64字符串。下面是我编写的使用HttpClient和HttpRequestMessage完成此操作的示例函数。我认为您可以采用这种结构,并轻松地将标题替换为您要尝试执行的操作。

public static void PostBase64PdfHttpClient(string recordID, string docName, string pdfB64)
    {
        string url = $"baseURL";
        HttpClient client = new HttpClient();
        var myBoundary = "------------ThIs_Is_tHe_bouNdaRY_";
        string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"UN:PW"));
        client.DefaultRequestHeaders.Add("Authorization", $"Basic {auth}");

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{url}/api-endpoint");
        request.Headers.Date = DateTime.UtcNow;
        request.Headers.Add("Accept", "application/json; charset=utf-8");
        MultipartContent mpContent = new MultipartContent("related", myBoundary);
        mpContent.Headers.TryAddWithoutValidation("Content-Type", $"multipart/related; boundary={myBoundary}");

        dynamic jObj = new Newtonsoft.Json.Linq.JObject(); jObj.ID = recordID; jObj.Name = docName;
        var jsonSerializeSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
        var json = JsonConvert.SerializeObject(jObj, jsonSerializeSettings);

        mpContent.Add(new StringContent(json, Encoding.UTF8, "application/json"));
        mpContent.Add(new StringContent(pdfB64, Encoding.UTF8, "application/pdf"));

        request.Content = mpContent;

        HttpResponseMessage response = client.SendAsync(request).Result;
    }