注:来自 https://blog.csdn.net/qq_16504067/article/details/121114404
推荐:SpringBoot-RestTemplate和okhttp

一、概述

在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。

在Java项目中调用第三方接口的方式有:

1、通过JDK网络类Java.net.HttpURLConnection;

2、通过common封装好的HttpClient;

3、通过Apache封装好的CloseableHttpClient;

4、通过SpringBoot-RestTemplate;

二、 Java调用第三方http接口的方式

2.1、通过JDK网络类Java.net.HttpURLConnection

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
实现过程:

  1. GET:
  2. 1、创建远程连接
  3. 2、设置连接方式(get、post、put。。。)
  4. 3、设置连接超时时间
  5. 4、设置响应读取时间
  6. 5、发起请求
  7. 6、获取请求数据
  8. 7、关闭连接
  9. POST:
  10. 1、创建远程连接
  11. 2、设置连接方式(get、post、put。。。)
  12. 3、设置连接超时时间
  13. 4、设置响应读取时间
  14. 5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
  15. 6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
  16. 7、设置传入参数的格式:(setRequestProperty)
  17. 8、设置鉴权信息:Authorization:(setRequestProperty)
  18. 9、设置参数
  19. 10、发起请求
  20. 11、获取请求数据
  21. 12、关闭连接

直接上代码:

  1. package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2. import org.springframework.lang.Nullable;
  3. import java.io.*;
  4. import java.net.HttpURLConnection;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. /**
  9. * @author riemann
  10. * @date 2019/05/24 23:42
  11. */
  12. public class HttpURLConnectionUtil {
  13. /**
  14. * Http get请求
  15. * @param httpUrl 连接
  16. * @return 响应数据
  17. */
  18. public static String doGet(String httpUrl){
  19. //链接
  20. HttpURLConnection connection = null;
  21. InputStream is = null;
  22. BufferedReader br = null;
  23. StringBuffer result = new StringBuffer();
  24. try {
  25. //创建连接
  26. URL url = new URL(httpUrl);
  27. connection = (HttpURLConnection) url.openConnection();
  28. //设置请求方式
  29. connection.setRequestMethod("GET");
  30. //设置连接超时时间
  31. connection.setReadTimeout(15000);
  32. //开始连接
  33. connection.connect();
  34. //获取响应数据
  35. if (connection.getResponseCode() == 200) {
  36. //获取返回的数据
  37. is = connection.getInputStream();
  38. if (null != is) {
  39. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  40. String temp = null;
  41. while (null != (temp = br.readLine())) {
  42. result.append(temp);
  43. }
  44. }
  45. }
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. } finally {
  49. if (null != br) {
  50. try {
  51. br.close();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. if (null != is) {
  57. try {
  58. is.close();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. //关闭远程连接
  64. connection.disconnect();
  65. }
  66. return result.toString();
  67. }
  68. /**
  69. * Http post请求
  70. * @param httpUrl 连接
  71. * @param param 参数
  72. * @return
  73. */
  74. public static String doPost(String httpUrl, @Nullable String param) {
  75. StringBuffer result = new StringBuffer();
  76. //连接
  77. HttpURLConnection connection = null;
  78. OutputStream os = null;
  79. InputStream is = null;
  80. BufferedReader br = null;
  81. try {
  82. //创建连接对象
  83. URL url = new URL(httpUrl);
  84. //创建连接
  85. connection = (HttpURLConnection) url.openConnection();
  86. //设置请求方法
  87. connection.setRequestMethod("POST");
  88. //设置连接超时时间
  89. connection.setConnectTimeout(15000);
  90. //设置读取超时时间
  91. connection.setReadTimeout(15000);
  92. //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
  93. //设置是否可读取
  94. connection.setDoOutput(true);
  95. connection.setDoInput(true);
  96. //设置通用的请求属性
  97. connection.setRequestProperty("accept", "*/*");
  98. connection.setRequestProperty("connection", "Keep-Alive");
  99. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  100. connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
  101. //拼装参数
  102. if (null != param && param.equals("")) {
  103. //设置参数
  104. os = connection.getOutputStream();
  105. //拼装参数
  106. os.write(param.getBytes("UTF-8"));
  107. }
  108. //设置权限
  109. //设置请求头等
  110. //开启连接
  111. //connection.connect();
  112. //读取响应
  113. if (connection.getResponseCode() == 200) {
  114. is = connection.getInputStream();
  115. if (null != is) {
  116. br = new BufferedReader(new InputStreamReader(is, "GBK"));
  117. String temp = null;
  118. while (null != (temp = br.readLine())) {
  119. result.append(temp);
  120. result.append("\r\n");
  121. }
  122. }
  123. }
  124. } catch (MalformedURLException e) {
  125. e.printStackTrace();
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. } finally {
  129. //关闭连接
  130. if(br!=null){
  131. try {
  132. br.close();
  133. } catch (IOException e) {
  134. e.printStackTrace();
  135. }
  136. }
  137. if(os!=null){
  138. try {
  139. os.close();
  140. } catch (IOException e) {
  141. e.printStackTrace();
  142. }
  143. }
  144. if(is!=null){
  145. try {
  146. is.close();
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. }
  150. }
  151. //关闭连接
  152. connection.disconnect();
  153. }
  154. return result.toString();
  155. }
  156. public static void main(String[] args) {
  157. String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
  158. System.out.println(message);
  159. }
  160. }

运行结果:

2.2 通过apache common封装好的HttpClient

httpClient的get或post请求方式步骤:

  1. 1.生成一个HttpClient对象并设置相应的参数;
  2. 2.生成一个GetMethod对象或PostMethod并设置响应的参数;
  3. 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
  4. 4.处理响应状态码;
  5. 5.若响应正常,处理HTTP响应内容;
  6. 6.释放连接。

导入如下jar包:

  1. <!--HttpClient-->
  2. <dependency>
  3. <groupId>commons-httpclient</groupId>
  4. <artifactId>commons-httpclient</artifactId>
  5. <version>3.1</version>
  6. </dependency>
  7. <!--fastjson-->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>fastjson</artifactId>
  11. <version>1.2.32</version>
  12. </dependency>

代码如下:

  1. package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.commons.httpclient.*;
  4. import org.apache.commons.httpclient.methods.GetMethod;
  5. import org.apache.commons.httpclient.methods.PostMethod;
  6. import org.apache.commons.httpclient.params.HttpMethodParams;
  7. import java.io.IOException;
  8. /**
  9. * @author riemann
  10. * @date 2019/05/25 0:58
  11. */
  12. public class HttpClientUtil {
  13. /**
  14. * httpClient的get请求方式
  15. * 使用GetMethod来访问一个URL对应的网页实现步骤:
  16. * 1.生成一个HttpClient对象并设置相应的参数;
  17. * 2.生成一个GetMethod对象并设置响应的参数;
  18. * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
  19. * 4.处理响应状态码;
  20. * 5.若响应正常,处理HTTP响应内容;
  21. * 6.释放连接。
  22. * @param url
  23. * @param charset
  24. * @return
  25. */
  26. public static String doGet(String url, String charset) {
  27. //1.生成HttpClient对象并设置参数
  28. HttpClient httpClient = new HttpClient();
  29. //设置Http连接超时为5秒
  30. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
  31. //2.生成GetMethod对象并设置参数
  32. GetMethod getMethod = new GetMethod(url);
  33. //设置get请求超时为5秒
  34. getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
  35. //设置请求重试处理,用的是默认的重试处理:请求三次
  36. getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
  37. String response = "";
  38. //3.执行HTTP GET 请求
  39. try {
  40. int statusCode = httpClient.executeMethod(getMethod);
  41. //4.判断访问的状态码
  42. if (statusCode != HttpStatus.SC_OK) {
  43. System.err.println("请求出错:" + getMethod.getStatusLine());
  44. }
  45. //5.处理HTTP响应内容
  46. //HTTP响应头部信息,这里简单打印
  47. Header[] headers = getMethod.getResponseHeaders();
  48. for(Header h : headers) {
  49. System.out.println(h.getName() + "---------------" + h.getValue());
  50. }
  51. //读取HTTP响应内容,这里简单打印网页内容
  52. //读取为字节数组
  53. byte[] responseBody = getMethod.getResponseBody();
  54. response = new String(responseBody, charset);
  55. System.out.println("-----------response:" + response);
  56. //读取为InputStream,在网页内容数据量大时候推荐使用
  57. //InputStream response = getMethod.getResponseBodyAsStream();
  58. } catch (HttpException e) {
  59. //发生致命的异常,可能是协议不对或者返回的内容有问题
  60. System.out.println("请检查输入的URL!");
  61. e.printStackTrace();
  62. } catch (IOException e) {
  63. //发生网络异常
  64. System.out.println("发生网络异常!");
  65. } finally {
  66. //6.释放连接
  67. getMethod.releaseConnection();
  68. }
  69. return response;
  70. }
  71. /**
  72. * post请求
  73. * @param url
  74. * @param json
  75. * @return
  76. */
  77. public static String doPost(String url, JSONObject json){
  78. HttpClient httpClient = new HttpClient();
  79. PostMethod postMethod = new PostMethod(url);
  80. postMethod.addRequestHeader("accept", "*/*");
  81. postMethod.addRequestHeader("connection", "Keep-Alive");
  82. //设置json格式传送
  83. postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
  84. //必须设置下面这个Header
  85. postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  86. //添加请求参数
  87. postMethod.addParameter("commentId", json.getString("commentId"));
  88. String res = "";
  89. try {
  90. int code = httpClient.executeMethod(postMethod);
  91. if (code == 200){
  92. res = postMethod.getResponseBodyAsString();
  93. System.out.println(res);
  94. }
  95. } catch (IOException e) {
  96. e.printStackTrace();
  97. }
  98. return res;
  99. }
  100. public static void main(String[] args) {
  101. System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
  102. System.out.println("-----------分割线------------");
  103. System.out.println("-----------分割线------------");
  104. System.out.println("-----------分割线------------");
  105. JSONObject jsonObject = new JSONObject();
  106. jsonObject.put("commentId", "13026194071");
  107. System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
  108. }
  109. }

运行结果:

 post请求的jsonObject 的参数也成功写入

2.3 通过Apache封装好的CloseableHttpClient

CloseableHttpClient是在HttpClient的基础上修改更新而来的,这里还涉及到请求头token的设置(请求验证),利用fastjson转换请求或返回结果字符串为json格式,当然上面两种方式也是可以设置请求头token、json的,这里只在下面说明。

导入如下jar包:

  1. <!--CloseableHttpClient-->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>httpclient</artifactId>
  5. <version>4.5.2</version>
  6. </dependency>
  7. <!--fastjson-->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>fastjson</artifactId>
  11. <version>1.2.32</version>
  12. </dependency>

代码如下:

  1. package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpStatus;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.StringEntity;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClientBuilder;
  11. import org.apache.http.util.EntityUtils;
  12. import java.io.IOException;
  13. import java.io.UnsupportedEncodingException;
  14. /**
  15. * @author riemann
  16. * @date 2019/05/25 1:35
  17. */
  18. public class CloseableHttpClientUtil {
  19. private static String tokenString = "";
  20. private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
  21. private static CloseableHttpClient httpClient = null;
  22. /**
  23. * 以get方式调用第三方接口
  24. * @param url
  25. * @param token
  26. * @return
  27. */
  28. public static String doGet(String url, String token) {
  29. //创建HttpClient对象
  30. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  31. HttpGet httpGet = new HttpGet(url);
  32. if (null != tokenString && !tokenString.equals("")) {
  33. tokenString = getToken();
  34. }
  35. //api_gateway_auth_token自定义header头,用于token验证使用
  36. httpGet.addHeader("api_gateway_auth_token",tokenString);
  37. httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  38. try {
  39. HttpResponse response = httpClient.execute(httpGet);
  40. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  41. //返回json格式
  42. String res = EntityUtils.toString(response.getEntity());
  43. return res;
  44. }
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. return null;
  49. }
  50. /**
  51. * 以post方式调用第三方接口
  52. * @param url
  53. * @param json
  54. * @return
  55. */
  56. public static String doPost(String url, JSONObject json) {
  57. if (null == httpClient) {
  58. httpClient = HttpClientBuilder.create().build();
  59. }
  60. HttpPost httpPost = new HttpPost(url);
  61. if (null != tokenString && tokenString.equals("")) {
  62. tokenString = getToken();
  63. }
  64. //api_gateway_auth_token自定义header头,用于token验证使用
  65. httpPost.addHeader("api_gateway_auth_token", tokenString);
  66. httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  67. try {
  68. StringEntity se = new StringEntity(json.toString());
  69. se.setContentEncoding("UTF-8");
  70. //发送json数据需要设置contentType
  71. se.setContentType("application/x-www-form-urlencoded");
  72. //设置请求参数
  73. httpPost.setEntity(se);
  74. HttpResponse response = httpClient.execute(httpPost);
  75. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  76. //返回json格式
  77. String res = EntityUtils.toString(response.getEntity());
  78. return res;
  79. }
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. } finally {
  83. if (httpClient != null){
  84. try {
  85. httpClient.close();
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. }
  91. return null;
  92. }
  93. /**
  94. * 获取第三方接口的token
  95. */
  96. public static String getToken() {
  97. String token = "";
  98. JSONObject object = new JSONObject();
  99. object.put("appid", "appid");
  100. object.put("secretkey", "secretkey");
  101. if (null == httpClient) {
  102. httpClient = HttpClientBuilder.create().build();
  103. }
  104. HttpPost httpPost = new HttpPost("http://localhost/login");
  105. httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  106. try {
  107. StringEntity se = new StringEntity(object.toString());
  108. se.setContentEncoding("UTF-8");
  109. //发送json数据需要设置contentType
  110. se.setContentType("application/x-www-form-urlencoded");
  111. //设置请求参数
  112. httpPost.setEntity(se);
  113. HttpResponse response = httpClient.execute(httpPost);
  114. //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
  115. //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
  116. //把response转为jsonObject
  117. JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
  118. if (result.containsKey("token")) {
  119. token = result.getString("token");
  120. }
  121. } catch (IOException e) {
  122. e.printStackTrace();
  123. }
  124. return token;
  125. }
  126. /**
  127. * 测试
  128. */
  129. public static void test(String telephone) {
  130. JSONObject object = new JSONObject();
  131. object.put("telephone", telephone);
  132. //首先获取token
  133. tokenString = getToken();
  134. String response = doPost("http://localhost/searchUrl", object);
  135. //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
  136. //List<Result> list = JSONObject.parseArray(response, Result.class);
  137. System.out.println(response);
  138. }
  139. public static void main(String[] args) {
  140. test("12345678910");
  141. }
  142. }

2.4 通过SpringBoot-RestTemplate

springBoot-RestTemple是上面三种方式的集大成者,代码编写更加简单,目前可以采用的调用第三方接口有:

  1. delete() 在特定的URL上对资源执行HTTP DELETE操作
  2. exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  3. execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  4. getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  5. getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  6. postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  7. postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  8. headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  9. optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  10. postForLocation() POST 数据到一个URL,返回新创建资源的URL
  11. put() PUT 资源到特定的URL

注意:目前标粗的为常用的

首先导入springboot的web包

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.4.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <!--CloseableHttpClient-->
  8. <dependency>
  9. <groupId>org.apache.httpcomponents</groupId>
  10. <artifactId>httpclient</artifactId>
  11. <version>4.5.2</version>
  12. </dependency>
  13. <!--spring restTemplate-->
  14. <!-- @ConfigurationProperties annotation processing (metadata for IDEs)
  15. 生成spring-configuration-metadata.json类,需要引入此类-->
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-configuration-processor</artifactId>
  19. <optional>true</optional>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-aop</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. <exclusions>
  29. <exclusion>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-tomcat</artifactId>
  32. </exclusion>
  33. </exclusions>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-jetty</artifactId>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. </dependencies>

在启动类同包下创建RestTemplateConfig.java类

 

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.http.client.ClientHttpRequestFactory;
  4. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  5. import org.springframework.web.client.RestTemplate;
  6. /**
  7. * @author riemann
  8. * @date 2019/05/25 2:16
  9. */
  10. @Configuration
  11. public class RestTemplateConfig {
  12. @Bean
  13. public RestTemplate restTemplate(ClientHttpRequestFactory factory){
  14. return new RestTemplate(factory);
  15. }
  16. @Bean
  17. public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
  18. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  19. factory.setConnectTimeout(15000);
  20. factory.setReadTimeout(5000);
  21. return factory;
  22. }
  23. }

然后在Service类(RestTemplateToInterface )中注入使用

具体代码如下:

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.swordfall.model.User;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.*;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.web.client.RestTemplate;
  7. /**
  8. * @author riemann
  9. * @date 2019/05/25 2:20
  10. */
  11. @Service
  12. public class RestTemplateToInterface {
  13. @Autowired
  14. private RestTemplate restTemplate;
  15. /**
  16. * 以get方式请求第三方http接口 getForEntity
  17. * @param url
  18. * @return
  19. */
  20. public User doGetWith1(String url){
  21. ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
  22. User user = responseEntity.getBody();
  23. return user;
  24. }
  25. /**
  26. * 以get方式请求第三方http接口 getForObject
  27. * 返回值返回的是响应体,省去了我们再去getBody()
  28. * @param url
  29. * @return
  30. */
  31. public User doGetWith2(String url){
  32. User user = restTemplate.getForObject(url, User.class);
  33. return user;
  34. }
  35. /**
  36. * 以post方式请求第三方http接口 postForEntity
  37. * @param url
  38. * @return
  39. */
  40. public String doPostWith1(String url){
  41. User user = new User("小白", 20);
  42. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
  43. String body = responseEntity.getBody();
  44. return body;
  45. }
  46. /**
  47. * 以post方式请求第三方http接口 postForEntity
  48. * @param url
  49. * @return
  50. */
  51. public String doPostWith2(String url){
  52. User user = new User("小白", 20);
  53. String body = restTemplate.postForObject(url, user, String.class);
  54. return body;
  55. }
  56. /**
  57. * exchange
  58. * @return
  59. */
  60. public String doExchange(String url, Integer age, String name){
  61. //header参数
  62. HttpHeaders headers = new HttpHeaders();
  63. String token = "asdfaf2322";
  64. headers.add("authorization", token);
  65. headers.setContentType(MediaType.APPLICATION_JSON);
  66. //放入body中的json参数
  67. JSONObject obj = new JSONObject();
  68. obj.put("age", age);
  69. obj.put("name", name);
  70. //组装
  71. HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
  72. ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
  73. String body = responseEntity.getBody();
  74. return body;
  75. }
  76. }

2.5 通过okhttp

应大家的响应,okhttp 现在也是蛮流行的,基于手机端很火,这里分享一下OkHttpClient客户端,业务代码get、post请求直接调用就好哈。

pom文件引入依赖包

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>3.10.0</version>
  5. </dependency>
  1. @Slf4j
  2. public class OkHttpClient {
  3. private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  4. private volatile static okhttp3.OkHttpClient client;
  5. private static final int MAX_IDLE_CONNECTION = Integer
  6. .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
  7. private static final long KEEP_ALIVE_DURATION = Long
  8. .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
  9. private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
  10. private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
  11. /**
  12. * 单例模式(双重检查模式) 获取类实例
  13. *
  14. * @return client
  15. */
  16. private static okhttp3.OkHttpClient getInstance() {
  17. if (client == null) {
  18. synchronized (okhttp3.OkHttpClient.class) {
  19. if (client == null) {
  20. client = new okhttp3.OkHttpClient.Builder()
  21. .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
  22. .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
  23. .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
  24. TimeUnit.MINUTES))
  25. .build();
  26. }
  27. }
  28. }
  29. return client;
  30. }
  31. public static String syncPost(String url, String json) throws IOException {
  32. RequestBody body = RequestBody.create(JSON, json);
  33. Request request = new Request.Builder()
  34. .url(url)
  35. .post(body)
  36. .build();
  37. try {
  38. Response response = OkHttpClient.getInstance().newCall(request).execute();
  39. if (response.isSuccessful()) {
  40. String result = response.body().string();
  41. log.info("syncPost response = {}, responseBody= {}", response, result);
  42. return result;
  43. }
  44. String result = response.body().string();
  45. log.info("syncPost response = {}, responseBody= {}", response, result);
  46. throw new IOException("三方接口返回http状态码为" + response.code());
  47. } catch (Exception e) {
  48. log.error("syncPost() url:{} have a ecxeption {}", url, e);
  49. throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
  50. }
  51. }
  52. public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
  53. Request request;
  54. final Request.Builder builder = new Request.Builder().url(url);
  55. try {
  56. if (!CollectionUtils.isEmpty(headParamsMap)) {
  57. final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
  58. .iterator();
  59. while (iterator.hasNext()) {
  60. final Map.Entry<String, Object> entry = iterator.next();
  61. builder.addHeader(entry.getKey(), (String) entry.getValue());
  62. }
  63. }
  64. request = builder.build();
  65. Response response = OkHttpClient.getInstance().newCall(request).execute();
  66. String result = response.body().string();
  67. log.info("syncGet response = {},responseBody= {}", response, result);
  68. if (!response.isSuccessful()) {
  69. throw new IOException("三方接口返回http状态码为" + response.code());
  70. }
  71. return result;
  72. } catch (Exception e) {
  73. log.error("remote interface url:{} have a ecxeption {}", url, e);
  74. throw new RuntimeException("三方接口返回异常");
  75. }
  76. }
  77. }

版权声明:本文为duende99原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/duende99/p/16200413.html