在java后端发送HTTPClient请求
简介
- HttpClient
遵循http协议
的客户端编程工具包
- 支持
最新
的http协议
部分依赖自动传递依赖了HttpClient的jar包
- 明明项目中没有引入 HttpClient 的Maven坐标,但是却可以直接使用HttpClient
- 原因是:阿里云的sdk依赖中传递依赖了HttpClient的jar包
发送get请求
@Testpublic void testGet() {// 创建HttpGet对象HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");// 创建HttpClient对象 用于发送请求// try-with-resources 语法 需要关闭的资源分别是 httpClient responsetry (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(httpGet)) {// 获取响应状态码int statusCode = response.getStatusLine().getStatusCode();System.out.println("响应状态码:" + statusCode); //响应状态码:200// 获取响应数据HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("响应数据:" + result); // 响应数据:{"code":1,"msg":null,"data":1}} catch (IOException e) {log.error("请求失败", e);e.printStackTrace();}}
发送post请求
/*** 测试HttpClient 发送post请求 需要提前启动项目 不然请求不到*/@Testpublic void testPost() {// 创建HttpPost对象HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");// 这个请求是有请求体的// 使用JsonObject构建请求体 更加高效简洁JsonObject jsonObject = new JsonObject();jsonObject.addProperty("username", "admin");jsonObject.addProperty("password", "123456");// 将json对象转为字符串 并设置编码格式 设置传输的数据格式 使用构造器和set方法都是可以设置的StringEntity stringEntity = null;try {stringEntity = new StringEntity(jsonObject.toString());stringEntity.setContentEncoding("UTF-8");stringEntity.setContentType("application/json");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}// 设置请求体httpPost.setEntity(stringEntity);// 创建HttpClient对象 用于发送请求// try-with-resources 语法 需要关闭的资源分别是 httpClient responsetry (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(httpPost)) {// 获取响应状态码int statusCode = response.getStatusLine().getStatusCode();System.out.println("响应状态码:" + statusCode); //响应状态码:200// 获取响应数据HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("响应数据:" + result); // 响应数据:{"code":1,"msg":null,"data":{"id":1,"userName":"admin","name":"管理员","token":"eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzI4MzgwOTk5fQ.Rm7UWZbDEU_06DJLfegcP31n-9g8AB-Jxa-49Zw-ttM"}}} catch (IOException e<