【问题标题】:POST xml string to URL with Java使用 Java 将 xml 字符串发布到 URL
【发布时间】:2015-10-21 22:43:26
【问题描述】:

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

【问题讨论】:

    标签: java post xmlhttprequest apache-httpcomponents


    【解决方案1】:

    httpcomponents 项目还包含一个更方便的用于 HTTP 的 fluent API 作为单独的下载(fluent-hc,maven groupdId:org.apache.httpcomponents,artifactId:fluent-hc)。使用 fluent-hc,带有字符串的 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 了解更多信息。

    【讨论】:

    • 有没有办法用这种方法将标题设置为 text/xml ? @user3653004
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2016-10-16
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多