使用Java将xml字符串POST到URL

时间:2015-07-30 14:09:41

标签: java post xmlhttprequest apache-httpcomponents

我已经下载了Apache Http Components 4.5 jar,我正在尝试使用此API对接受xml作为SSTRING NOT A FILE的URL发出POST请求。我在网上找到的所有示例都要求您定义PostMethod对象。这个Object应该是http组件api的一部分,但是PostMethod的包不存在。我很肯定我把所有的罐子都正确地添加到了我的类路径中。我有什么办法可以使用,或者我可以做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:1)

httpcomponents项目还包含一个更方便的HTTP流畅的API作为单独的下载(fluent-hc,maven groupdId:org.apache.httpcomponents,artifactId:fluent-hc)。使用fluent-hc,带有String的POST如下所示:

import org.apache.http.client.fluent.*;

Request post = Request.Post(url).bodyString(contentString, ContentType.APPLICATION_XML).addHeader("Accept", "application/xml");
Response resp = post.execute();
String answerContent = resp.returnContent().asString();

有关详情,请参阅https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html