HttpClient知识总结
一.HttpClient简介
HttpClient是一个可以让java应用程序使用http协议访问网络资源的客户端编程工具包。(JDK中java.net包也提供了基本的HTTP访问资源功能,但是不能做复杂处理)
二.HttpClient包
在maven中导入httpClient包(如下),或者在官网中下载jar包手动导入到项目中。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 请检查是否有更新的版本 -->
</dependency>
三.HttpClient应用
1.Get请求,无参数
//1.创建一个client对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建Get请求对象,在请求中输入url
HttpGet get=new HttpGet("http://www.baidu.com");
//3.发送请求,返回响应数据
CloseableHttpResponse res = client.execute(get);
//4.获取响应的状态码
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
//5.处理响应数据
HttpEntity entity = res.getEntity();
String content = EntityUtils.toString(entity, "utf-8");
System.out.println(content);
//6.关闭链接
client.close();
2.Get请求,有参数
//1.创建client对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建一个封装URI的对象,在该对象中可以给定请求参数
URIBuilder bui = new URIBuilder("http://www.baidu.com/s");
bui.addParameter("word","西游记");
//3.创建一个Get请求对象
HttpGet get = new HttpGet(bui.build());
//4.发送请求对象,并且获得响应数据
CloseableHttpResponse res = client.execute(get);
//5.获取请求码
int code = res.getStatusLine().getStatusCode();
System.out.println("请求码:"+code);
//6.获取响应内容,处理响应数据
HttpEntity entity = res.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
//7.关闭client
client.close();
3.Post请求,无参数
//1.创建Client对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建一个Post对象,在请求中输入url
HttpPost post = new HttpPost("http://www.baidu.com/");
//3.发送post请求,并获得响应数据
CloseableHttpResponse res = client.execute(post);
//4.获得响应码
int code = res.getStatusLine().getStatusCode();
System.out.println("Post无参数响应码:"+code);
//5.处理响应数据
HttpEntity entity = res.getEntity();
String content = EntityUtils.toString(entity, "utf-8");
System.out.println(content);
//6.关闭client
client.close();
4.Post请求,有参数
// 1.创建client对象
CloseableHttpClient client = HttpClients.createDefault();
// 2.创建post对象
HttpPost post = new HttpPost("https://cn.bing.com/search?");
// 3.设定参数,将参数加入到post对象中
List<BasicNameValuePair> list=new ArrayList<>();//参数先存入数组中
list.add(new BasicNameValuePair("q","响应码302"));
StringEntity entity = new UrlEncodedFormEntity(list, "utf-8");//将参数做字符串的转换
post.setEntity(entity);//将参数加入到post对象中
// 4.发送请求,获得响应数据
CloseableHttpResponse res = client.execute(post);
// 5.获得响应码
int code = res.getStatusLine().getStatusCode();
System.out.println("post带参数,响应码:"+code);
// 6.处理响应数据
HttpEntity entity1 = res.getEntity();
String content = EntityUtils.toString(entity1, "utf-8");
System.out.println(content);
// 7.关闭client
client.close();
5.Post请求,带JSON格式参数
// 1.创建client对象
CloseableHttpClient client = HttpClients.createDefault();
// 2.创建post对象
HttpPost post = new HttpPost("https://cn.bing.com/search?");
// 3.设置Post传入的JSON字符串参数
String json="{\"q\":\"响应码302\"}";
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(entity);
// 4.发送请求,获取响应数据
CloseableHttpResponse res = client.execute(post);
// 5.返回响应码
int code = res.getStatusLine().getStatusCode();
System.out.println("post请求带Json参数:"+code);
// 6.处理响应数据
HttpEntity entity1 = res.getEntity();
String content = EntityUtils.toString(entity1, "utf-8");
System.out.println(content);
6.HttpClient自定义工具类的使用
根据上述内容,我们可以将HttpClient封装成一个工具类HttpClientUtil
6.1编写工具类HttpClient
public class HttpClientUtil {
//GET请求,带参数
public static String doGet(String url, Map<String,String>param){
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString="";
CloseableHttpResponse response=null;
//创建uri
try {
URIBuilder builder = new URIBuilder(url);
if(param!=null){
for(String key:param.keySet()){
builder.addParameter(key,param.get(key));
}
}
URI uri=builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//执行请求
response=httpClient.execute(httpGet);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
resultString= EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response!=null){
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
//GET请求,无参数
public static String doGet(String url){
return doGet(url,null);
}
//Post请求,带参数
public static String doPost(String url,Map<String,String> param){
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
try {
//创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//创建参数列表
if(param!=null){
List<NameValuePair> paramList=new ArrayList<>();
for(String key:param.keySet()){
paramList.add(new BasicNameValuePair(key,param.get(key)));
}
//模拟表单
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
//执行http请求
response=httpClient.execute(httpPost);
resultString=EntityUtils.toString(response.getEntity(),"utf-8");
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
response.close();
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return resultString;
}
//Post请求,不带参数
public static String doPost(String url){
return doPost(url,null);
}
//Post请求,带Json参数
public static String doPostJson(String url,String json){
//创建client对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
try {
// 创建http Post请求
HttpPost httpPost = new HttpPost(url);
//创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
//执行http请求
response=httpClient.execute(httpPost);
resultString=EntityUtils.toString(response.getEntity(),"utf-8");
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return resultString;
}
}
6.2测试工具类HttpClientUitl
public static void httpClientUtilTest(){
String url="https://cn.bing.com/search?";
Map<String,String> param=new HashMap<>();
param.put("q","响应302");
String result=HttpClientUtil.doPost(url,param);
System.out.println("结果展示:"+result);
}