java httppost查看报文_Java面试题 消息中间件
时间: 2024-01-14 14:05:12 浏览: 70
在 Java 中,我们可以使用 HttpClient 库来发送 HTTP 请求,并使用 HttpPost 类来发送 POST 请求。为了查看 POST 请求的报文,我们可以在发送请求之前,将请求体打印出来。示例代码如下:
```java
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class MyHttpClient {
public static void main(String[] args) throws IOException {
// 创建 HttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPost 请求
HttpPost httpPost = new HttpPost("http://localhost:8080/myServlet");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String requestBody = "{\"name\":\"Tom\",\"age\":18}";
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
// 打印请求体
System.out.println("Request Body: " + requestBody);
// 发送请求并获取响应
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 处理响应
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println("Response Body: " + responseBody);
// 关闭资源
httpResponse.close();
httpClient.close();
}
}
```
上述代码中,我们使用 HttpClient 库创建了一个 HttpClient 实例,并创建了一个 HttpPost 请求。在设置完请求头和请求体之后,我们通过 System.out.println() 函数将请求体打印出来。当我们发送 POST 请求时,控制台会输出请求体,并打印响应体。
阅读全文