使用 HttpClient 发送空内容

sending empty content with HttpClient

我正在尝试连接到另一家公司的 API。 从文档中有 ::

even with your GET request, you'll need to include the Java equivalent of curl_setopt($ch, CURLOPT_POSTFIELDS, $content), and you can set $data equal to an empty array.

$content 在他们的例子中是一个空的 JSON 数组。

我正在使用 org.apache.commons.httpclient

我不确定如何将 post 字段添加到 org.apache.commons.httpclient.methods.GetMethod 或者是否可能。

我尝试伪造内容长度为 2,但 GET 超时(可能是在寻找我没有提供的内容。如果我删除内容长度,我会从 api 收到无效响应服务器)

   HttpClient client = new HttpClient();
   GetMethod method = new GetMethod("https://api.xxx.com/account/");
   method.addRequestHeader("Content-Type", "application/json");
   method.addRequestHeader("X-Public-Key", APKey);
   method.addRequestHeader("X-Signed-Request-Hash", "xxx");
   method.addRequestHeader("Content-Length", "2");

   int statusCode = client.executeMethod(method);

我认为 GetMethod 不包括任何附加请求的方法 body,因为 GET 请求不应该有 body。 (但是 body 实际上也没有被禁止 - 请参阅:HTTP GET with request body 。)

您正在尝试使用以不同语言和不同客户端库编写的文档,因此您将不得不反复试验。听起来他们希望没有 body 的请求,而您已经有了。他们没有充分的理由要求 "Content-Length" 和 GET,但如果是这种情况,请尝试将其设置为 0。

我就是这样解决这个问题的

创建了这个class

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
    public HttpGetWithEntity() {
        super();
    }
    public HttpGetWithEntity(URI uri) {
        super();
        setURI(uri);
    }
    public HttpGetWithEntity(String uri) {
        super();
        setURI(URI.create(uri));
    }
    @Override
    public String getMethod() {
        return HttpGet.METHOD_NAME;
    }
}

那么调用函数看起来像

public JSONObject get(JSONObject payload, String URL) throws Exception {

    JSONArray jsonArray = new JSONArray();
    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpGetWithEntity myGet = new HttpGetWithEntity(WeeblyAPIHost+URL);
    myGet.setEntity( new StringEntity("[]") );
    myGet.setHeader("Content-Type", "application/json");
    myGet.setHeader("X-Public-Key", APIKey);
    HttpResponse response = client.execute(myGet);

    JSONParser parser = new JSONParser();
    Object obj = parser.parse( EntityUtils.toString(response.getEntity(), "UTF-8") ) ;
    JSONObject jsonResponse = (JSONObject) obj;

    return jsonResponse;

}