简介:
HttpClient是Apache Jakarta common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
说明:
httpClient是现在企业中使用较多的跨域请求的方式.
1.引入jar包文件
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
2.入门Demo
package com.jt.web.httpclient;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class TestHttpClient {
/**
* 1.定义httpClient对象
* 2.定义访问的url
* 3.定义请求方式
* 4.发起http请求
* 5.获取响应结果
* @throws IOException
* @throws ClientProtocolException
*/
//@Test
public void test01() throws ClientProtocolException, IOException{
//定义http请求对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//定义url
String url = "http://news.cctv.com/special/jujiao/2017/808/index.shtml";
//定义请求方式
HttpGet httpGet = new HttpGet(url);
//发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
System.out.println("恭喜您请求发送正确");
String html = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(html);
}else{
System.out.println("对不起请求失败");
}
}
//@Test
public void testPost() throws ClientProtocolException, IOException{
CloseableHttpClient client = HttpClients.createDefault();
String url = "http://www.iqiyi.com/v_19rrak1hy8.html";
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = client.execute(post);
String html = EntityUtils.toString(response.getEntity());
System.out.println(html);
}
}
作者博客:http://www.major818.com