HttpClient 远程接口调用方式
远程接口调用方式HttpClient
问题:现在我们已经开发好了接口了,那该如何调用这个接口呢?
答:使用Httpclient客户端。
Httpclient简介
什么是httpclient
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
httpclient作用
在java代码中,发送Http请求。通常用来实现远程接口调用。
HttpClient测试
在工程中添加httpclient的pom依赖。
1
2
3
4
|
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> |
执行GET请求
1 public static void doGet(){ 2 // 创建Httpclient对象 3 CloseableHttpClient httpclient = HttpClients.createDefault(); 4 5 // 创建http GET请求 6 HttpGet httpGet = new HttpGet("http://www.oschina.net/"); 7 8 CloseableHttpResponse response = null; 9 try { 10 // 执行请求 11 response = httpclient.execute(httpGet); 12 System.out.println(response.getStatusLine()); 13 // 判断返回状态是否为200 14 if (response.getStatusLine().getStatusCode() == 200) { 15 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); 16 System.out.println("内容长度:" + content.length()); 17 } 18 }catch(Exception e){ 19 e.printStackTrace(); 20 21 } finally { 22 if (response != null) { 23 try { 24 response.close(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 try { 30 httpclient.close(); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 }
执行GET带参数
1 public static void doGetParam(){ 2 // 创建Httpclient对象 3 CloseableHttpClient httpclient = HttpClients.createDefault(); 4 CloseableHttpResponse response = null; 5 try { 6 7 // 定义请求的参数 8 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "数据库").build(); 9 10 System.out.println(uri); 11 12 // 创建http GET请求 13 HttpGet httpGet = new HttpGet(uri); 14 15 // 执行请求 16 response = httpclient.execute(httpGet); 17 // 判断返回状态是否为200 18 if (response.getStatusLine().getStatusCode() == 200) { 19 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); 20 System.out.println(content); 21 } 22 }catch(Exception e){ 23 e.printStackTrace(); 24 25 }finally { 26 if (response != null) { 27 try { 28 response.close(); 29 } catch (IOException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 } 34 try { 35 httpclient.close(); 36 } catch (IOException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 } 41 }
执行post请求
1 public static void doPost(){ 2 // 创建Httpclient对象 3 CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); 4 5 // 创建http POST请求 6 HttpPost httpPost = new HttpPost("http://www.oschina.net/"); 7 8 CloseableHttpResponse response = null; 9 try { 10 // 执行请求 11 response = httpclient.execute(httpPost); 12 System.out.println(response.getStatusLine()); 13 // 判断返回状态是否为200 14 if (response.getStatusLine().getStatusCode() == 200) { 15 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); 16 System.out.println(content); 17 } 18 }catch(Exception e){ 19 e.printStackTrace(); 20 21 }finally { 22 if (response != null) { 23 try { 24 response.close(); 25 } catch (IOException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } 29 } 30 try { 31 httpclient.close(); 32 } catch (IOException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } 36 } 37 }
执行post带参数
1 public static void doPostParam() throws Exception{ 2 // 创建Httpclient对象 3 CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); 4 5 // 创建http POST请求 6 HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); 7 8 // 设置2个post参数,一个是scope、一个是q 9 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 10 parameters.add(new BasicNameValuePair("scope", "project")); 11 parameters.add(new BasicNameValuePair("q", "java")); 12 // 构造一个form表单式的实体 13 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); 14 // 将请求实体设置到httpPost对象中 15 httpPost.setEntity(formEntity); 16 17 CloseableHttpResponse response = null; 18 try { 19 // 执行请求 20 response = httpclient.execute(httpPost); 21 System.out.println(response.getStatusLine()); 22 // 判断返回状态是否为200 23 if (response.getStatusLine().getStatusCode() == 200) { 24 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); 25 System.out.println(content); 26 } 27 } finally { 28 if (response != null) { 29 response.close(); 30 } 31 httpclient.close(); 32 } 33 }
httpclient常见问题及解决方案
请求参数乱码
设置请求的编码格式:
1 obj.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
响应HTTP/1.1 403 Forbidden
原因:网站设置了反爬虫机制,禁止非法访问。
解决方案:伪装浏览器。
1 obj.addHeader("User-Agent"," Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/31.0.1650.63")
封装通用工具类HttpClientUtils
1 package org.chu.ego.base.utils; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6 import java.util.Map; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.NameValuePair; 10 import org.apache.http.client.entity.UrlEncodedFormEntity; 11 import org.apache.http.client.methods.CloseableHttpResponse; 12 import org.apache.http.client.methods.HttpGet; 13 import org.apache.http.client.methods.HttpPost; 14 import org.apache.http.client.utils.URIBuilder; 15 import org.apache.http.impl.client.CloseableHttpClient; 16 import org.apache.http.impl.client.HttpClientBuilder; 17 import org.apache.http.impl.client.HttpClients; 18 import org.apache.http.impl.client.LaxRedirectStrategy; 19 import org.apache.http.message.BasicNameValuePair; 20 import org.apache.http.util.EntityUtils; 21 /** 22 * --发送get请求的api 23 * CloseableHttpClient类 ,client实现类 24 * HttpClients类 ,client工具类,用于创建客户端对象。 25 * CloseableHttpResponse接口,请求的响应对象 26 * URIBuilder类 :url构建类,用于设置get请求的路径变量 27 * HttpGet类 :get请求的发送对象 28 * EntityUtils类 实体处理类 29 * 30 * --发送post 请求使用的api 31 * CloseableHttpClient类 32 * HttpClientBuilder client构建对象,用于创建客户端对象。 33 * LaxRedirectStrategy类,post请求重定向的策略 34 * CloseableHttpResponse 请求的响应对象 35 * HttpPost post请求的发送对象 36 * NameValuePair 类,用于设置参数值 37 * UrlEncodedFormEntity:用于设置表单参数给发送对象HttpPost 38 * 39 * @author ranger 40 * 41 */ 42 public class HttpClientUtils { 43 44 public static String doGet(String url,Map<String, String> params){ 45 46 //获取httpclient客户端 47 CloseableHttpClient httpclient = HttpClients.createDefault(); 48 49 String resultString = ""; 50 51 CloseableHttpResponse response = null; 52 53 try { 54 URIBuilder builder = new URIBuilder(url); 55 56 if(null!=params){ 57 for (String key:params.keySet()) { 58 builder.setParameter(key, params.get(key)); 59 } 60 } 61 62 HttpGet get = new HttpGet(builder.build()); 63 64 65 response = httpclient.execute(get); 66 67 System.out.println(response.getStatusLine()); 68 69 if(200==response.getStatusLine().getStatusCode()){ 70 HttpEntity entity = response.getEntity(); 71 resultString = EntityUtils.toString(entity, "utf-8"); 72 } 73 74 } catch (Exception e) { 75 76 e.printStackTrace(); 77 } finally { 78 if(null!=response){ 79 try { 80 response.close(); 81 } catch (IOException e) { 82 // TODO Auto-generated catch block 83 e.printStackTrace(); 84 } 85 } 86 if(null!=httpclient){ 87 try { 88 httpclient.close(); 89 } catch (IOException e) { 90 // TODO Auto-generated catch block 91 e.printStackTrace(); 92 } 93 } 94 } 95 96 return resultString; 97 } 98 99 public static String doGet(String url){ 100 return doGet(url, null); 101 } 102 103 public static String doPost(String url,Map<String,String> params){ 104 /** 105 * 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。 106 * 107 * 获取httpclient客户端 108 */ 109 CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build(); 110 111 String resultString = ""; 112 113 CloseableHttpResponse response = null; 114 115 try { 116 117 118 HttpPost post = new HttpPost(url); 119 120 List<NameValuePair> paramaters = new ArrayList<>(); 121 122 if(null!=params){ 123 for (String key : params.keySet()) { 124 paramaters.add(new BasicNameValuePair(key,params.get(key))); 125 } 126 127 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (paramaters); 128 129 post.setEntity(formEntity); 130 } 131 132 133 /** 134 * HTTP/1.1 403 Forbidden 135 * 原因: 136 * 有些网站,设置了反爬虫机制 137 * 解决的办法: 138 * 设置请求头,伪装浏览器 139 */ 140 post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"); 141 142 response = httpclient.execute(post); 143 144 System.out.println(response.getStatusLine()); 145 146 if(200==response.getStatusLine().getStatusCode()){ 147 HttpEntity entity = response.getEntity(); 148 resultString = EntityUtils.toString(entity, "utf-8"); 149 } 150 151 } catch (Exception e) { 152 153 e.printStackTrace(); 154 } finally { 155 if(null!=response){ 156 try { 157 response.close(); 158 } catch (IOException e) { 159 // TODO Auto-generated catch block 160 e.printStackTrace(); 161 } 162 } 163 if(null!=httpclient){ 164 try { 165 httpclient.close(); 166 } catch (IOException e) { 167 // TODO Auto-generated catch block 168 e.printStackTrace(); 169 } 170 } 171 } 172 173 return resultString; 174 } 175 176 public static String doPost(String url){ 177 return doPost(url, null); 178 } 179 180 }