不啰嗦,实用,明白。
首先导入包,原先httpclient是在apache的common包下,后来好像被分到独立的httpclient下了。
在4.x版本以下四个是核心吧:
httpcore-4.4.1.jar
httpclient-4.5.jar
commons-codec-1.9.jar
commons-logging-1.2.jar
导入包之后,直接写代码,不用tomcat直接运行就行:
public class HttpClientTest {
public static void main(String[] args){
new HttpClientTest().get();
}
/**
* 发送 get请求
*/
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget
HttpGet httpget = new HttpGet("http://www.baidu.com/");
//输出URI
System.out.println("executing request : " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
//关闭连接,释放资源
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是一个简单的httpclient的创建以及使用过程,使用静态方法HttpClients.createDefault()创建一个可关闭的CloseableHttpClient,然后new HttpGet,然后httpclient.execute(httpget)用http客户端运行httpget,返回值是请求的目标内容CloseableHttpResponse,需要的响应内容都在CloseableHttpResponse里头,可以通过方法取到。
这就是一个浏览器模拟的过程:
1、输入URL地址,创建一个httpget请求
2、创建一个httpclient,相当于浏览器
3、使用httpclient发送httpget请求,相当于浏览器的访问
4、得到一个返回值CloseableHttpResponse,相当于浏览器访问后得到响应的内容
5、需要查看的响应内容通过CloseableHttpResponse的方法取出
使用httpclient,关键是要能够模拟我们想要执行的行为,能够灵活拆解浏览器功能,自由组合:
0、基本使用
1、随意拼接请求内容的能力
2、根据需要获取响应内容的能力
3、对浏览器各个功能支持的能力
4、实现浏览器无法实现的功能