创建HttpClient发送请求、接收响应
Get请求简介
- 1). 创建HttpClient对象,可以使用
HttpClients.createDefault()
; - 2). 如果是无参数的GET请求,则直接使用构造方法
HttpGet(String url
)创建HttpGet对象即可; - 3)如果是带参数GET请求,则可以先使用
URIBuilder
(String url)创建对象,再调用addParameter
(Stringparam, String value)`, 或setParameter(String param, String)
value)来设置请求参数,并调用build()方法构建一个URI对象。 - 4). 创建HttpResponse,调用HttpClient对象的
execute(
HttpUriRequest
request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String
name)等方法可获取服务器的响应头; - 5)调用
HttpResponse的getEntity()
方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()
可以获取响应状态码。 - 6). 释放连接。
构建一个Maven项目,引入如下依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
get无参数
如果是无参数的GET请求,则直接使用构造方法HttpGet(String url
)创建HttpGet对象即可
/**
*普通的GET请求
*/
public class DoGET {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
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");
//内容写入文件
FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");
System.out.println("内容长度:"+content.length());
}
} finally {
if (response != null) {
response.close();
}
//相当于关闭浏览器