HttpClient

HttpClient-------一款便于在程序内发送get和post请求的工具

介绍:

HttpClient是Apache Jakarta Common下的子项目,可以用来提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包,并且支持HTTP协议最新的版本和建议。(用于便捷发送get和post请求)

maven坐标

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

使用案例

发送Get请求

public void testGet() throw Exception{
	//创建httpclient对象
	CloseableHttpClient httpClient = HttpClient.createDefault();
	 
	//创建请求对象,发送请求,接收结果
    HttpGet httpGet = new HttpGet("请求地址");
    CloseableHttepResponse response = httpClient.execute(httpGet);
    
    //获取服务器返回的状态码和数据
    int statusCode = response.getStatusLine().getStatusCode();//响应码
    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);//body为服务器返回的数据
    
    //关闭资源
    response.close();
    httpClient.close();
}

发送Post请求

public void testpost() throw Exception{
    //创建httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    
    //创建请求对象
    HttpPost httpPost = new HttpPost("请求地址");
    
    //把需要加的信息封装为json对象
    JOSNObject 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();//响应码
    
    //获取返回的数据
    HttpEntity entity1 = response.getEntity();
    String body = EntityUtils.toSting(entity1);
    
    //关闭资源
    response.close();
    httpClient.close();
    
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值