HttpClient 基本操作

概念

构造http请求并发送

实现

导入依赖

xml 复制代码
<dependency>  
    <groupId>org.apache.httpcomponent</groupId>  
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

发送get请求

ini 复制代码
@Test  
public void testGET() throws Exception{  
    //创建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();  
    String body = EntityUtils.toString(entity);  
    System.out.println("服务端返回的数据为:" + body);  

    //关闭资源  
    response.close();  
    httpClient.close();  
}

发送post请求

ini 复制代码
/**  
* 测试通过httpclient发送POST方式的请求  
*/  
@Test  
public void testPOST() throws Exception{  
    // 创建httpclient对象  
    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 entity = new StringEntity(jsonObject.toString());  
    //指定请求编码方式  
    entity.setContentEncoding("utf-8");  
    //数据格式  
    entity.setContentType("application/json");  
    httpPost.setEntity(entity);  

    //发送请求  
    CloseableHttpResponse response = httpClient.execute(httpPost);  

    //解析返回结果  
    int statusCode = response.getStatusLine().getStatusCode();  
    System.out.println("响应码为:" + statusCode);  

    HttpEntity entity1 = response.getEntity();  
    String body = EntityUtils.toString(entity1);  
    System.out.println("响应数据为:" + body);  

    //关闭资源  
    response.close();  
    httpClient.close();  
}
相关推荐
Jinkey几秒前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
葫芦和十三8 分钟前
图解 MongoDB 06|模式演进:无 schema 是优势还是债
后端·mongodb·agent
葫芦和十三8 小时前
图解 MongoDB 05|文档模型设计:内嵌 vs 引用,反范式不是免费午餐
后端·mongodb·agent
不能放弃治疗11 小时前
单 Agent 实现模式
后端
IT_陈寒13 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
fliter14 小时前
最后一块拼图:用 bitvec 构造 IPv4 包,真正做出自己的 Ping
后端
fliter15 小时前
用 Rust 解析并生成 ICMP 包:checksum、nom 与 cookie-factory
后端
蝎子莱莱爱打怪15 小时前
XZLL-IM干货系列 03|消息 ID 设计:一个 UUID 搞不定的事,我用两个 ID 解决了
后端·面试·开源
fliter15 小时前
从 panic 到 Result:用 Rust 重新整理一个 ping 项目的错误处理
后端
森蓝情丶16 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端