maven项目:pom.xml导入httpclient依赖
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
模拟发送get请求
HttpGet get = new HttpGet("测试的接口地址");
get.setHeader("请求头字段", "字段值");
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(get);
响应报文获取
Header[] allHeaders = httpResponse.getAllHeaders();
System.out.println("响应头:"+Arrays.toString(allHeaders));
HttpEntity httpEntity = httpResponse.getEntity();
String body = EntityUtils.toString(httpEntity);
System.out.println("响应体:"+body);
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:"+statusCode);
模拟发送post请求
HttpPost post = new HttpPost("测试的接口地址");
post.setHeader("Content-Type", "application/json");
String json = "复制入参json格式的请求报文";
post.setEntity(new StringEntity(json,"utf-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(post);