所以我一直在 stackoverflow 和 google 上做了大量的研究,试图回答我的以下问题,但我一直找不到任何可以帮助我 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 version="1.0"encoding="UTF-8"standalone="no"?订阅电子邮件="patricia@test.intershop.de"firstName="Patricia"gender="Female"lastName="Miller"title="Ms."/
(注意:我删除了 < 和 > 括号。它们出现在它们应该出现的位置!)
但是,我收到了 400 错误。这里有什么想法吗?我知道我有正确的 header ,URL 是正确的,等等。这绝对与我对有效载荷所做的事情有关。任何想法将不胜感激!!
最好!
最佳答案
在您预期的负载中,“电子邮件”、“名字”等是订阅元素的子元素。根据代码,它们被添加为“订阅”元素的属性。如果您需要“电子邮件”、“名字”等作为子元素,您应该使用 appendChild() 而不是 setAttribute()。
Element email = doc.createElement("email");
email.appendChild(document.createTextNode("patricia@test.intershop.de"));
subscription.appendChild(email);
关于java - 使用 HttpClient 发送带有 HTTP POST 请求的 XML 有效负载--Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17413423/