1

因此,我一直在对 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”独立=“否”?订阅 email="patricia@test.intershop.de" firstName="Patricia" gender="Female" lastName="Miller" title="Ms."/

(注意:我删除了 < 和 > 括号。它们出现在它们应该出现的地方!)

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

最好的!

4

1 回答 1

3

在您预期的有效负载中,“电子邮件”、“名字”等是 Subscription 元素的子元素。根据代码,它们被添加为您的“订阅”元素的属性。如果您需要 'email'、'firstname' 等作为子元素,则应使用 appendChild() 而不是 setAttribute()。

Element email = doc.createElement("email");
email.appendChild(document.createTextNode("patricia@test.intershop.de"));
subscription.appendChild(email);
于 2013-07-02T02:07:44.650 回答