一、HttpClient是什么
HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。
HttpClient 是一个HTTP通信库、一个工具包,它只提供一个通用浏览器应用程序所期望的功能子集,与浏览器相比是没有界面的。
把HttpClient 看做是 ajax 中的 XMLHttpRequest对象
二、HttpClient能做什么
HttpClient的功能包括但不限于:
模拟浏览器发送HTTP请求,发送请求参数,并接收响应。
RPC接口调用
爬取网页源码
三、HttpClient优点
基于标准、纯净的java语言。实现了HTTP1.0和HTTP1.1;
以可扩展的面向对象的结构实现了HTTP全部的方法(GET, POST等7种方法);
支持HTTPS协议;
通过HTTP代理建立透明的连接
四、调用接口获取数据例子
1、pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
2、获取ip信息例子get/post
//获取ip信息例子
public class TestClient {
@Test
public void testGet(){
//发起get请求,编程方式处理http请求。
String url="https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip=60.25.188.64";
//1.创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建HttpGet对象
HttpGet httpGet = new HttpGet(url);
//3.执行请求,使用client对象的方法,执行请求后获取返回结果
//CloseableHttpResponse是返回结果,相当于HttpServletResponse
try{
CloseableHttpResponse response = client.execute(httpGet);
//从response获取应答信息
if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//4.获取数据
//response.getEntity().getContent();//数据
String json = EntityUtils.toString(response.getEntity());
System.out.println("访问ip的应答结果:"+json);
}
}catch (Exception e){
e.printStackTrace();
} finally {
//5.关闭资源
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//post请求
@Test
public void testHttpPost(){
//1.创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建HttpPost对象,表示post请求
String url = "https://restapi.amap.com/v3/ip";
HttpPost httpPost = new HttpPost(url);
//3.准备post请求的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加参数 BasicNameValuePair类,实现了NameValuePair接口
// BasicNameValuePair(参数名,参数值);
params.add( new BasicNameValuePair("key","0113a13c88697dcea6a445584d535837"));
//params.add( new BasicNameValuePair("ip","60.25.188.64"));
params.add( new BasicNameValuePair("ip","111.201.50.56"));
//4.设置HttpPost使用参数
try{
httpPost.setEntity( new UrlEncodedFormEntity(params));
//5.执行请求
CloseableHttpResponse res = client.execute(httpPost);
//6.读取数据
if( res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String json = EntityUtils.toString(res.getEntity());
System.out.println("json="+json);
}
} catch (Exception e){
e.printStackTrace();
} finally {
//关闭资源
try{
client.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}