打印Apache HttpClient PostMethod调用的有效负载

时间:2016-04-01 17:19:07

标签: groovy apache-commons-httpclient

我正在使用Apache HttpClient 3.1向URL发出HTTP Post请求,其中我传递了一个JSON请求实体和一些类似的参数..

    HttpMethod method = new PostMethod("https://starfleet.reliant/commandConsole")
   // assume there is already a varaible json which has valid JSON in it
    StringRequestEntity requestEntity = new StringRequestEntity(json.toString(), "application/json", "UTF-8")
    method.setRequestEntity(requestEntity);
    method.addParameter("format","json");
    method.addParameter("prefixCode","16309");

有没有办法可以打印出整个有效载荷的样子(包括JSON请求实体和参数)?换句话说,我想确切地看到发布到服务器的内容。

如果我只是......

println("Sending this ${method.toString()}")

这只是打印......

  Sending this org.apache.commons.httpclient.methods.PostMethod@3f67dcc1 

当然不是我想要的。

1 个答案:

答案 0 :(得分:0)

对于HttpClient 3x:

尝试使用像这样的Object Mapper来获取请求:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(requestEntity));

相关性:

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
</dependency>

对于HttpClient 4x +: 尝试从apache (documented here)

查看EntityUtils

会是这样的

String str = EntityUtils.toString(method.getRequestEntity());
System.out.println(str);