HttpClient

HttpClient 是 客户端编程工具包。能够用来构造发送Http请求。当我们需要客户端发送http请求时(例如微信登入,请求微信登入的接口),就会用到它。

在java中使用HttpClient需要导入他的依赖

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

核心API

  • HttpClient(接口)
  • HttpClients (用来构建HttpClient)
  • CloseableHttpClient(实现类)
  • HttpGet
  • HttpPost

发送请求步骤

1.创建HttpClient对象

CloseableHttpClient httpclient=HttpClients.createDefault();

2.创建Http请求对象      3.调用HttpClient的excute方法发送请求

get请求

HttpGet httpget =new HttpGet("url");
CloseableHttpResponse response=httpClient.excute(httpGet);

post请求

HttpPost httpPost =new HttpPost("url");
StringEntity entity=new StringEntity(json格式数据);
HttpPost.setEntity(entity);//设置请求参数
CloseableHttpResponse response=httpClient.excute(httpGet);

4.获取服务端返回的数据

//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:"+statusCode);

HttpEntity entity = response.getEntity();//获取响应数据对象
String body = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为:"+body);

5.关闭资源

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值