如何使用流畅的Apache组件

Joh*_*ard 13 java apache-httpclient-4.x

我正在尝试使用Apache Components(4.3)的示例构建一个http POST - http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fluent.html.不幸的是,我收到一个错误,我无法找到如何解决.

我之前使用过前者HttpClient- 所以这是我第一次使用组件.

以下是代码片段:

String address = "http://1.1.1.1/services/postPositions.php";
String response = Request.Post(address)
        .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
        .execute().returnContent().asString();
System.out.println(response);
Run Code Online (Sandbox Code Playgroud)

当我运行该代码时,我得到一个例外:

Exception in thread "main" java.lang.IllegalStateException: POST request cannot enclose an entity
    at org.apache.http.client.fluent.Request.body(Request.java:299)
    at org.apache.http.client.fluent.Request.bodyString(Request.java:331)
    at PostJson.main(PostJson.java:143)
Run Code Online (Sandbox Code Playgroud)

我也尝试构建一个表单元素并使用该bodyForm()方法 - 但我得到了同样的错误.

swK*_*wKK 6

我遇到了同样的问题,修复方法是使用Apache Client 4.3.1.

请求似乎已更改:

  • 在4.3.1他们使用公共 HttpRequestBase
  • 在最新版本中,他们使用受保护的包 InternalHttpRequest

  • 根据https://issues.apache.org/jira/browse/HTTPCLIENT-1474修复.HttpClient 4.3.3的解决方法是将HC Fluent降级到版本4.3.2 (4认同)