一、HttpClient
两个系统间如何互相访问?两个tomcat上的项目如何互相访问
采用HttpClient实现跨系统的接口调用。
1.2、 什么是HttpClient
官网:http://hc.apache.org/index.html
特点:
-
HttpClient别名:HttpComponents
-
HttpClient可以发送get、post、put、delete、…等请求
-
1.3、 HttpClient入门案例
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
1.3.1、 发起Get请求
1创建一个客户端 CloseableHttpClient
2创建一个get方法请求实例 HttpGet
3发送请求 execute
4获取响应的头信息
5获取响应的主题内容
6关闭响应对象
使用HttpClient发起Get请求的案例代码:
public class DoGET {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建HttpGet请求,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
CloseableHttpResponse response = null;
try {
// 执行请求,相当于敲完地址后按下回车。获取响应
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应,获取数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
// 关闭资源
response.close();
}
// 关闭浏览器
httpclient.close();
}
}
}