使用HttpClient——Java通过HTTPPOST请求发送XML有效负载



所以我一直在stackoverflow和谷歌上做了很多工作,试图回答我的以下问题,但我一直找不到任何可以帮助我100%完成这项工作的东西。我敢肯定,除了一个小错误,我什么都有,但很明显,你们可能无论如何都有建议,所以去做吧!

现在我们开始:我一直在使用HTTPClient在几个不同的环境中测试API,我使用HTTPPost方法来接受JSON有效载荷,但现在我正在尝试使用XML发送有效载荷,我遇到了一些问题。我正在创建的XML字符串(在下面的代码中)似乎是正确的。。。所以我很困惑为什么这不起作用。另外:大部分DOM代码都来自互联网(用于构建XML负载),所以也可以随意提出疑问。。。

我的代码如下:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element subscription = doc.createElement("subscription");
doc.appendChild(subscription);
subscription.setAttribute("email", "patricia@test.intershop.de");
etc....
etc....
etc....
etc....
DOMSource domSource = new DomSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String XMLpayload = writer.toString();
[name of my HttpRequest].setEntity(new StringEntity(XMLpayload));
[name of my HttpResponse] = client.execute(request);

现在。。。我希望实现以下所示的有效载荷:

<subscription>
    <email>patricia@test.intershop.de</email>
    <firstName>Patricia</firstName>
    <lastName>Miller</lastName>
    <title>Ms.</title>
    <gender>Female</gender>
</subscription>

当我打印出我当前发送的有效载荷时,它看起来如下:

xml版本="1.0"编码="UTF-8"独立="否"?订阅电子邮件="patricia@test.intershop.de"firstName="Patricia"gender="Female"lastName="Miller"title="Ms。"/

(注意:我移除了<和>支架。它们出现在应该出现的地方!)

但是,我收到一个400错误。有什么想法吗?我知道我有合适的标题,URL是正确的,等等。这绝对是我对负载所做的事情。任何想法都将不胜感激!!

最好!

在您预期的有效负载中,包括"电子邮件"、"第一时间"等。。是Subscription元素的子元素。根据代码,它们将作为"subscription"元素的属性添加。如果您需要"电子邮件"、"第一时间"等。。作为子元素,应该使用appendChild()而不是setAttribute()。

Element email = doc.createElement("email");
email.appendChild(document.createTextNode("patricia@test.intershop.de"));
subscription.appendChild(email);

最新更新