1. 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2.使用
package com.sky;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@Slf4j
@SpringBootTest
public class TestHttpClient {
@Test
public void doGet () throws IOException {
//1.创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.创建HttpGet对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//3.使用HttpClient发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
//4.解析响应
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//5.获取响应体
HttpEntity entity = response.getEntity();
System.out.println(entity);
//6.获取响应内容
String string = EntityUtils.toString(entity);
System.out.println(string);
//6.关闭资源
httpClient.close();
response.close();
}
@Test
public void doPost() throws JSONException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//设置请求体
JSONObject jsonObject=new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
//发起请求
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode = " + statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity);
System.out.println("string = " + string);
}
}