远程接口调用方式HttpClient
问题:现在我们已经开发好了接口了,那该如何调用这个接口呢?
答:使用Httpclient客户端。
 
Httpclient简介
什么是httpclient
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
下载地址:http://hc.apache.org/
 
httpclient作用
在java代码中,发送Http请求。通常用来实现远程接口调用。
HttpClient测试
在工程中添加httpclient的pom依赖。
  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. </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. response = httpclient.execute(get);
  65.  
  66. System.out.println(response.getStatusLine());
  67.  
  68. if(200==response.getStatusLine().getStatusCode()){
  69. HttpEntity entity = response.getEntity();
  70. resultString = EntityUtils.toString(entity, "utf-8");
  71. }
  72.  
  73. } catch (Exception e) {
  74.  
  75. e.printStackTrace();
  76. } finally {
  77. if(null!=response){
  78. try {
  79. response.close();
  80. } catch (IOException e) {
  81. // TODO Auto-generated catch block
  82. e.printStackTrace();
  83. }
  84. }
  85. if(null!=httpclient){
  86. try {
  87. httpclient.close();
  88. } catch (IOException e) {
  89. // TODO Auto-generated catch block
  90. e.printStackTrace();
  91. }
  92. }
  93. }
  94.  
  95. return resultString;
  96. }
  97.  
  98. public static String doGet(String url){
  99. return doGet(url, null);
  100. }
  101.  
  102. public static String doPost(String url,Map<String,String> params){
  103. /**
  104. * 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
  105. *
  106. * 获取httpclient客户端
  107. */
  108. CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();
  109.  
  110. String resultString = "";
  111.  
  112. CloseableHttpResponse response = null;
  113.  
  114. try {
  115.  
  116. HttpPost post = new HttpPost(url);
  117.  
  118. List<NameValuePair> paramaters = new ArrayList<>();
  119.  
  120. if(null!=params){
  121. for (String key : params.keySet()) {
  122. paramaters.add(new BasicNameValuePair(key,params.get(key)));
  123. }
  124.  
  125. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (paramaters);
  126.  
  127. post.setEntity(formEntity);
  128. }
  129.  
  130. /**
  131. * HTTP/1.1 403 Forbidden
  132. * 原因:
  133. * 有些网站,设置了反爬虫机制
  134. * 解决的办法:
  135. * 设置请求头,伪装浏览器
  136. */
  137. 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");
  138.  
  139. response = httpclient.execute(post);
  140.  
  141. System.out.println(response.getStatusLine());
  142.  
  143. if(200==response.getStatusLine().getStatusCode()){
  144. HttpEntity entity = response.getEntity();
  145. resultString = EntityUtils.toString(entity, "utf-8");
  146. }
  147.  
  148. } catch (Exception e) {
  149.  
  150. e.printStackTrace();
  151. } finally {
  152. if(null!=response){
  153. try {
  154. response.close();
  155. } catch (IOException e) {
  156. // TODO Auto-generated catch block
  157. e.printStackTrace();
  158. }
  159. }
  160. if(null!=httpclient){
  161. try {
  162. httpclient.close();
  163. } catch (IOException e) {
  164. // TODO Auto-generated catch block
  165. e.printStackTrace();
  166. }
  167. }
  168. }
  169.  
  170. return resultString;
  171. }
  172.  
  173. public static String doPost(String url){
  174. return doPost(url, null);
  175. }
  176.  
  177. }
 
 
 

HttpClient 远程接口调用方式的更多相关文章

  1. HttpClient远程接口调用-实名认证

    1.HttpClient远程接口调用 1)用户注册 注册按钮button提交表单时,要return false form表单 <!-- action="http://localhost ...

  2. libcurl 接口调用方式

    http://hi.baidu.com/tracyu1026/item/bb6d5def4292b10b570f1d48 libcurl提供了一组C语言API函数直接调用.首先需要提到的两个函数就是c ...

  3. SmartRoute之远程接口调用和负载

    基于接口的调用远比基于基础消息交互来得更简单和便于维护,特别在业务展现上,接口作为业务表现更适合其便利性.为了让SmartRoute更适合业务应用集成,在新的一年开始SmartRoute集成了远程接口 ...

  4. 【RPC】远程接口调用实例 的几种方式比较

    pring中,用JMS搞RPC时会用到: org.springframework.jms.remoting.JmsInvokerServiceExporter org.springframework. ...

  5. 带SSL证书的httpclient 远程接口工具类

    package com.iups.wx.util; import java.io.IOException; import java.io.UnsupportedEncodingException; i ...

  6. RMI(远程接口调用)

    1. RMI的原理: RMI系统结构,在客户端和服务器端都有几层结构. 方法调用从客户对象经占位程序(Stub).远程引用层(Remote Reference Layer)和传输层(Transport ...

  7. HttpClient两种调用方式

    一.参数字符串 /** * HttpClient请求接口 * @return 成功:音频字节 失败:null */ public static byte[] requestBaiduAudio(Str ...

  8. HTTP接口调用方式

    1.get方式,设置调用方式为get,参数直接在url中包含,直接调用获取返回值即可 2.post方式,content为application/x-www-form-urlencoded  ,参数格式 ...

  9. SpringBoot远程接口调用-RestTemplate使用

    在web服务中,调度远程url是常见的使用场景,最初多采用原生的HttpClient,现采用Spring整合的RestTemplate工具类进行.实操如下: 1. 配置 主要用以配置远程链接的相关参数 ...

随机推荐

  1. useMemo优化React Hooks程序性能(九)

    useMemo主要用来解决使用React hooks产生的无用渲染的性能问题.使用function的形式来声明组件,失去了shouldCompnentUpdate(在组件更新之前)这个生命周期,也就是 ...

  2. Apache-dbutils 简介及事务处理

    一:commons-dbutils简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化 ...

  3. Tosca case status PLANNED,IN-WORK,COMPLETED 对应的图标

    #PLANNED #IN-WORK #COMPLETED

  4. 005 DOM02

    在上一篇DOM的基础上,继续案例的实践. 一:案例 1.禁用文本框 <!DOCTYPE html> <html lang="en"> <head> ...

  5. leetcode 290. Word Pattern 、lintcode 829. Word Pattern II

    290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...

  6. Linux 在 TOP 命令中切换内存的显示单位

    顶部的内存信息可以在top运行时按E切换,每次切换转换率为1000,只是没有单位,切换的单位为 k,m,g,t,p: 1. 2. 3., 4. 底下的进程信息按e切换,每次切换转换率为1000,切换的 ...

  7. log4j 异常时在日志文件里面显示空的。

    如下图所示,输入的时候不要写 e.getStackTrace() 一般情况下不会出问题,但有时候就会出问题 解决方案

  8. 定时备份删除数据库sql

    1.备份数据库 mkdir -p /home/mysql/mysql_bak/ vi mysql_bak.sh #!/bin/bash #Shell Command For Backup MySQL ...

  9. C#DbHelperOleDb,Access数据库帮助类 (转)

    /// <summary>/// 编 码 人:苏飞/// 联系方式:361983679  /// 更新网站:[url=http://www.sufeinet.com/thread-655- ...

  10. LeetCode_303. Range Sum Query - Immutable

    303. Range Sum Query - Immutable Easy Given an integer array nums, find the sum of the elements betw ...