HttpClient入门
简介
HttpClient
是 Apache HttpComponents 项目中的一个开源的 Java HTTP 客户端库,用于发送 HTTP 请求和处理 HTTP 响应。它提供了一组强大而灵活的 API,使得在 Java 程序中执行 HTTP 请求变得相对简单
maven依赖
org.apache.httpcomponents httpclient 4.5.2或者导入阿里云oss
com.aliyun.oss aliyun-sdk-oss里面包含了httpclient
核心API:-
- HttpClient.
- HttpClients
- CloseableHttpClient.
- HttpGet
- HttpPost
发送请求步骤
创建HttpClient对象
创建http请求对象
调用HttpClient的execute方法发送请求
示例get
@Test
public void httpGetTest() throws IOException {
//获取创建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
//创建http请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//调用HttpClient的execute方法发送请求,并获得响应
HttpResponse response = httpClient.execute(httpGet);
//获得响应的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//获得响应体
HttpEntity entity = response.getEntity();
System.out.println(entity);
}
示例post
@Test
public void httpPostTest() throws IOException, JSONException {
//获取创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建http请求对象
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("utf8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
//调用HttpClient的execute方法发送请求,并获得响应
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
System.out.println(entity);
}