httpclient GET 和POST 请求
GET请求
@SpringBootTest
public class HttpClientTest {
/**
* 测试通过httpclient发送get请求
*/
@Test
public void testGET() throws IOException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求,接受响应结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码:" + statusCode);
//获得具体的响应数据
//获得响应体
HttpEntity entity = response.getEntity();
//解析HttpEntity对象 转化为string字符串
String body = EntityUtils.toString(entity);
//响应体body
System.out.println("服务端返回的数据为:" + body);
//关闭资源
response.close();
httpClient.close();
}
POST请求
/**
* 测试通过httpclient发送post请求
*/
@Test
public void testPOST() throws IOException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//post需要传参数 设置请求参数65-76
//用jsonobject 把字符串转出来
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
//jsonObject.toJSONString() 构造JSON格式的字符串
//设置请求参数
StringEntity entity = new StringEntity(jsonObject.toJSONString());
//指定请求编码方法
entity.setContentEncoding("UTF-8");
//指定数据格式
entity.setContentType("application/json");
//数据封装到 httpPost 里面去
httpPost.setEntity(entity);
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//解析返回的结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("响应码为:" + statusCode);
//具体响应回来的数据
HttpEntity entity1 = response.getEntity();
//响应体body
String body = EntityUtils.toString(entity1);
System.out.println("响应数据为"+body);
//关闭资源
response.close();
httpClient.close();
}
}