HttpClient入门
2024-01-01 22:37:09
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);
}
文章来源:https://blog.csdn.net/qq_62646841/article/details/135329349
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!