【发布时间】:2021-02-26 22:40:40
【问题描述】:
我正在尝试将 xml 发送到服务器,但它总是抛出异常 Malformed request: Premature end of file.. 。使用邮递员效果很好,但使用HttpClient 却不行,我认为问题出在headers 上,服务器需要的是Content-Type", "application/xml,我无法做到这一点
我该如何解决?
尝试
//HttpClient
HttpClient hClient = new HttpClient();
hClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/xml");
//post
var contentString = new StringContent(xml, Encoding.UTF8, "application/xml");
HttpResponseMessage response = hClient.PostAsync(URL_FINAL, contentString).GetAwaiter().GetResult();
var resultContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
xml
<?xml version="1.0" encoding="utf-16"?>
<payment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<mode>default</mode>
<method>creditCard</method>
<sender>
<name>Meu Nome</name>
<email>email@gmail.com</email>
<phone>
<areaCode>17</areaCode>
<number>9999999999</number>
</phone>
<documents>
<document>
<type>CPF</type>
<value>9999999999</value>
</document>
</documents>
<hash>5e5240axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxea8a</hash>
</sender>
<currency>BRL</currency>
<notificationURL>https://dominio.com/StatusPagamentoTransaction</notificationURL>
<items>
<item>
<id>2</id>
<description>produto</description>
<quantity>2</quantity>
<amount>2.00</amount>
</item>
</items>
<extraAmount>0.00</extraAmount>
<reference>R748</reference>
<shipping>
<addressRequired>false</addressRequired>
</shipping>
<creditCard>
<token>91999999999999999999b0f</token>
<installment>
<quantity>1</quantity>
<value>2.00</value>
</installment>
<holder>
<name>nome proprietario cartao</name>
<documents>
<document>
<type>CPF</type>
<value>99999999999</value>
</document>
</documents>
<birthDate>18/12/1964</birthDate>
<phone>
<areaCode>17</areaCode>
<number>99999999</number>
</phone>
</holder>
<billingAddress>
<street>rua A</street>
<number>3333</number>
<district>bairro</district>
<city>cidade</city>
<state>SP</state>
<country>BRA</country>
<postalCode>05407002</postalCode>
</billingAddress>
</creditCard>
</payment>
例外
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?><errors><error><code>11213</code><message>Malformed request: Premature end of file..</message></error></errors>
【问题讨论】:
-
您是否通过 Fiddler 查看过您的请求以了解它是如何发送的?
-
@Andy 不。 Fiddle 是如何工作的,它对我有什么帮助?
-
谷歌“fiddler web debugger tool”——它真的很容易使用,尽管他们已经把它变成了一个必须注册帐户的 PITA。
-
@Andy 我正在使用邮递员,它正在工作。现在我尝试了 Fiddler 并且也可以使用
标签: c# asp.net-mvc dotnet-httpclient