【问题标题】:Sending XML payloads with HTTP POST request using HttpClient--Java使用 HttpClient--Java 通过 HTTP POST 请求发送 XML 有效负载
【发布时间】:2013-06-29 02:27:45
【问题描述】:

因此,我在 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 版本=“1.0”编码=“UTF-8”独立=“否”?订阅 email="patricia@test.intershop.de" firstName="Patricia" gender="Female" lastName="Miller" title="Ms."/

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

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

最好的!

【问题讨论】:

  • 您的代码生成的 xml 有效负载是否正确?每个代码,电子邮件、名字等都设置为您的“订阅”元素的属性。如果你需要'email'、'firstname'等作为子元素,你应该使用 appendChild() 而不是 setAttribute()
  • 请返回并输入&lt;&gt; 并将整个内容缩进4 个空格,这样我们就不必猜测或读懂您的想法。如果都是一行,则将其保留在一行中并让 SO 将其显示在滚动代码小部件中。
  • @user1573133 你的评论(没有第一句话)应该是一个答案。
  • @JimGarrison:谢谢。添加为答案。

标签: java http xmlhttprequest httpclient


【解决方案1】:

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

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

【讨论】:

  • 哇,非常感谢!这就是我感到困惑的事情。我对 Java 中的 XML 和 JSON 非常陌生,因此获得正确的有效负载很困难,但这非常有帮助!要去试试看!我觉得这就是问题所在!谢谢!!!
  • 成功了!你是救生员!!!这是我喜欢编程的简单事情。如此微妙,却又如此重要。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多