Springboot整合RestTemplate、java调用http请求方式、

叁歲伎倆 2022-12-11 03:20 816阅读 0赞

目录

概述

方式一:使用JDK原生提供的net

1、HttpURLConnection类实现

2、URLConnection类实现

3、Socket类实现

方式二:apache的HttpClient开发

1、直接使用apache的HttpClient开发

2、通过Apache封装好的CloseableHttpClient

方式三:RestTemplate

1、简述RestTemplate

2.配置

3、使用

GET 请求

POST 请求

PUT 请求

DELETE 请求

通用方法 exchange

4、自定义设置

手动指定转换器(HttpMessageConverter)

设置底层连接方式

设置拦截器(ClientHttpRequestInterceptor)

设置请求头


概述

通过向指定的第三方地址发送对应格式的数据以便换取所需数据这一需求是平时开发经常碰到的需求。几种常见的方式如下

方式一:使用JDK原生提供的net

包下的HttpURLConnection、URLConnection、Socket三个类都可实现,无需其他jar包;

1、HttpURLConnection类实现

HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

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

过程

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

2、URLConnection类实现

  1. package uRLConnection;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. public class URLConnectionHelper {
  9. public static String sendRequest(String urlParam) {
  10. URLConnection con = null;
  11. BufferedReader buffer = null;
  12. StringBuffer resultBuffer = null;
  13. try {
  14. URL url = new URL(urlParam);
  15. con = url.openConnection();
  16. //设置请求需要返回的数据类型和字符集类型
  17. con.setRequestProperty("Content-Type", "application/json;charset=GBK");
  18. //允许写出
  19. con.setDoOutput(true);
  20. //允许读入
  21. con.setDoInput(true);
  22. //不使用缓存
  23. con.setUseCaches(false);
  24. //得到响应流
  25. InputStream inputStream = con.getInputStream();
  26. //将响应流转换成字符串
  27. resultBuffer = new StringBuffer();
  28. String line;
  29. buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
  30. while ((line = buffer.readLine()) != null) {
  31. resultBuffer.append(line);
  32. }
  33. return resultBuffer.toString();
  34. }catch(Exception e) {
  35. e.printStackTrace();
  36. }
  37. return "";
  38. }
  39. public static void main(String[] args) {
  40. String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  41. System.out.println(sendRequest(url));
  42. }
  43. }

3、Socket类实现

  1. package socket;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStreamWriter;
  8. import java.net.Socket;
  9. import java.net.URLEncoder;
  10. import javax.net.ssl.SSLSocket;
  11. import javax.net.ssl.SSLSocketFactory;
  12. public class SocketForHttpTest {
  13. private int port;
  14. private String host;
  15. private Socket socket;
  16. private BufferedReader bufferedReader;
  17. private BufferedWriter bufferedWriter;
  18. public SocketForHttpTest(String host,int port) throws Exception{
  19. this.host = host;
  20. this.port = port;
  21. /**
  22. * http协议
  23. */
  24. // socket = new Socket(this.host, this.port);
  25. /**
  26. * https协议
  27. */
  28. socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);
  29. }
  30. public void sendGet() throws IOException{
  31. //String requestUrlPath = "/z69183787/article/details/17580325";
  32. String requestUrlPath = "/";
  33. OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
  34. bufferedWriter = new BufferedWriter(streamWriter);
  35. bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");
  36. bufferedWriter.write("Host: " + this.host + "\r\n");
  37. bufferedWriter.write("\r\n");
  38. bufferedWriter.flush();
  39. BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
  40. bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
  41. String line = null;
  42. while((line = bufferedReader.readLine())!= null){
  43. System.out.println(line);
  44. }
  45. bufferedReader.close();
  46. bufferedWriter.close();
  47. socket.close();
  48. }
  49. public void sendPost() throws IOException{
  50. String path = "/";
  51. String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("张三", "utf-8") + "&" +
  52. URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");
  53. // String data = "name=zhigang_jia";
  54. System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);
  55. OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
  56. bufferedWriter = new BufferedWriter(streamWriter);
  57. bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");
  58. bufferedWriter.write("Host: " + this.host + "\r\n");
  59. bufferedWriter.write("Content-Length: " + data.length() + "\r\n");
  60. bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
  61. bufferedWriter.write("\r\n");
  62. bufferedWriter.write(data);
  63. bufferedWriter.write("\r\n");
  64. bufferedWriter.flush();
  65. BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
  66. bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
  67. String line = null;
  68. while((line = bufferedReader.readLine())!= null)
  69. {
  70. System.out.println(line);
  71. }
  72. bufferedReader.close();
  73. bufferedWriter.close();
  74. socket.close();
  75. }
  76. public static void main(String[] args) throws Exception {
  77. /**
  78. * http协议测试
  79. */
  80. //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);
  81. /**
  82. * https协议测试
  83. */
  84. SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);
  85. try {
  86. forHttpTest.sendGet();
  87. // forHttpTest.sendPost();
  88. } catch (IOException e) {
  89. e.printStackTrace();
  90. }
  91. }
  92. }

方式二:apache的HttpClient开发

1、直接使用apache的HttpClient开发

使用方便,但依赖于第三方jar包,相关maven依赖如下:

  1. <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
  2. <dependency>
  3. <groupId>commons-httpclient</groupId>
  4. <artifactId>commons-httpclient</artifactId>
  5. <version>3.1</version>
  6. </dependency

简单测试

  1. package httpClient;
  2. import java.io.IOException;
  3. import org.apache.commons.httpclient.HttpClient;
  4. import org.apache.commons.httpclient.HttpException;
  5. import org.apache.commons.httpclient.methods.GetMethod;
  6. import org.apache.commons.httpclient.methods.PostMethod;
  7. import org.apache.commons.httpclient.params.HttpMethodParams;
  8. public class HttpClientHelper {
  9. public static String sendPost(String urlParam) throws HttpException, IOException {
  10. // 创建httpClient实例对象
  11. HttpClient httpClient = new HttpClient();
  12. // 设置httpClient连接主机服务器超时时间:15000毫秒
  13. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  14. // 创建post请求方法实例对象
  15. PostMethod postMethod = new PostMethod(urlParam);
  16. // 设置post请求超时时间
  17. postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  18. postMethod.addRequestHeader("Content-Type", "application/json");
  19. httpClient.executeMethod(postMethod);
  20. String result = postMethod.getResponseBodyAsString();
  21. postMethod.releaseConnection();
  22. return result;
  23. }
  24. public static String sendGet(String urlParam) throws HttpException, IOException {
  25. // 创建httpClient实例对象
  26. HttpClient httpClient = new HttpClient();
  27. // 设置httpClient连接主机服务器超时时间:15000毫秒
  28. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  29. // 创建GET请求方法实例对象
  30. GetMethod getMethod = new GetMethod(urlParam);
  31. // 设置post请求超时时间
  32. getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  33. getMethod.addRequestHeader("Content-Type", "application/json");
  34. httpClient.executeMethod(getMethod);
  35. String result = getMethod.getResponseBodyAsString();
  36. getMethod.releaseConnection();
  37. return result;
  38. }
  39. public static void main(String[] args) throws HttpException, IOException {
  40. String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  41. System.out.println(sendPost(url));
  42. System.out.println(sendGet(url));
  43. }
  44. }

比较全的工具类

导入jar

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.32</version>
  5. </dependency>
  6. import com.alibaba.fastjson.JSONObject;
  7. import org.apache.commons.httpclient.*;
  8. import org.apache.commons.httpclient.methods.GetMethod;
  9. import org.apache.commons.httpclient.methods.PostMethod;
  10. import org.apache.commons.httpclient.params.HttpMethodParams;
  11. import java.io.IOException;
  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. }

2、通过Apache封装好的CloseableHttpClient

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

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

方式三:RestTemplate

1、简述RestTemplate

  1. spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的HttpClientRestTemplate是一种更优雅的调用RESTful服务的方式。
  2. RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如Apache HttpComponentsNettyOkHttp等其它HTTP library
  3. 其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdkhttp请求。

2.配置

只需有以下jar就可使用

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

把 RestTemplate交给spring管理

  1. package com.rails.travel.conf;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.http.client.ClientHttpRequestFactory;
  5. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  6. import org.springframework.web.client.RestTemplate;
  7. /**
  8. * RestTemplate配置类
  9. */
  10. @Configuration
  11. public class RestTemplateConfig {
  12. //2.0后使用下面没有注释的方式 在注入的同时设置连接时间,这种注释的也可以,但是没有设置超时时间
  13. /*@Bean
  14. public RestTemplate restTemplate(RestTemplateBuilder builder){
  15. return builder.build();
  16. }*/
  17. @Bean
  18. public RestTemplate restTemplate(ClientHttpRequestFactory factory){
  19. return new RestTemplate(factory);
  20. }
  21. @Bean
  22. public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
  23. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  24. factory.setReadTimeout(5000);//单位为ms
  25. factory.setConnectTimeout(5000);//单位为ms
  26. return factory;
  27. }
  28. }

3、使用

GET 请求

在 RestTemplate 中,和 GET 请求相关的方法有如下几个:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0NDkxNTA4_size_16_color_FFFFFF_t_70

这里的方法一共有两类,getForEntity 和 getForObject,每一类有三个重载方法

getForEntity

既然 RestTemplate 发送的是 HTTP 请求,那么在响应的数据中必然也有响应头,如果开发者需要获取响应头的话,那么就需要使用 getForEntity 来发送 HTTP 请求,此时返回的对象是一个 ResponseEntity 的实例。这个实例中包含了响应数据以及响应头

第一个参数是 url ,url 中有一个占位符 {1} ,如果有多个占位符分别用 {2} 、 {3} … 去表示,第二个参数是接口返回的数据类型,最后是一个可变长度的参数,用来给占位符填值。在返回的 ResponseEntity 中,可以获取响应头中的信息,其中 getStatusCode 方法用来获取响应状态码, getBody 方法用来获取响应数据, getHeaders 方法用来获取响应头

  1. String url = "http://localhost/hello?name={1}";
  2. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, "张三");
  3. StringBuffer sb = new StringBuffer();
  4. HttpStatus statusCode = responseEntity.getStatusCode();
  5. String body = responseEntity.getBody();

当然,这里参数的传递除了这一种方式之外,还有另外两种方式,也就是 getForEntity 方法的另外两个重载方法。

第一个是占位符不使用数字,而是使用参数的 key,同时将参数放入到一个 map 中。map 中的 key 和占位符的 key 相对应,map 中的 value 就是参数的具体值,例如还是上面的请求,利用 map 来传递参数,请求方式如下:

  1. Map<String, Object> map = new HashMap<>();
  2. String url = "http://" + host + ":" + port + "/hello?name={name}";
  3. map.put("name", name);
  4. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);

这种方式传参可能看起来更直观一些。

第二个是使用 Uri 对象,使用 Uri 对象时,参数可以直接拼接在地址中,例如下面这样:

  1. String url = "http://" + host + ":" + port + "/hello?name="+ URLEncoder.encode(name,"UTF-8");
  2. URI uri = URI.create(url);
  3. ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);

需要注意的是,这种传参方式,参数如果是中文的话,需要对参数进行编码,使用 URLEncoder.encode 方法来实现。

getForObject

getForObject 方法和 getForEntity 方法类似,getForObject 方法也有三个重载的方法,参数和 getForEntity 一样;主要说下 getForObject 和 getForEntity 的差异,这两个的差异主要体现在返回值的差异上, getForObject 的返回值就是服务提供者返回的数据,使用 getForObject 无法获取到响应头。例如,还是上面的请求,利用 getForObject 来发送 HTTP 请求,结果如下:

  1. String url = "http://" + host + ":" + port + "/hello?name=" + URLEncoder.encode(name, "UTF-8");
  2. URI uri = URI.create(url);
  3. String s = restTemplate.getForObject(uri, String.class);

注意,这里返回的 s 就是 provider 的返回值,如果开发者只关心 provider 的返回值,并不关系 HTTP 请求的响应头,那么可以使用该方法。

POST 请求

和 GET 请求相比,RestTemplate 中的 POST 请求多了一个类型的方法,如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0NDkxNTA4_size_16_color_FFFFFF_t_70 1

可以看到,post 请求的方法类型除了 postForEntity 和 postForObject 之外,还有一个 postForLocation。这里的方法类型虽然有三种,但是这三种方法重载的参数基本是一样的,因此这里我还是以 postForEntity 方法为例,来剖析三个重载方法的用法,最后再重点说下 postForLocation 方法。

postForEntity

在 POST 请求中,参数的传递可以是 key/value 的形式,也可以是 JSON 数据,分别来看:

a: 传递 key/value 形式的参数

  1. int port = instance.getPort();
  2. String url = "http://" + host + ":" + port + "/hello2";
  3. MultiValueMap map = new LinkedMultiValueMap();
  4. map.add("name", name);
  5. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);
  6. return responseEntity.getBody();

postForEntity 方法第一个参数是请求地址,第二个参数 map 对象中存放着请求参数 key/value,第三个参数则是返回的数据类型。当然这里的第一个参数 url 地址也可以换成一个 Uri 对象,效果是一样的。这种方式传递的参数是以 key/value 形式传递的,在 post 请求中,也可以按照 get 请求的方式去传递 key/value 形式的参数,传递方式和 get 请求的传参方式基本一致

  1. String host = "myhost";
  2. int port = "2020";
  3. String url = "http://" + host + ":" + port + "/hello2?name={1}";
  4. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class,name);
  5. return responseEntity.getBody();

此时第二个参数可以直接传一个 null。

b:传递 JSON 数据

上面介绍的是 post 请求传递 key/value 形式的参数,post 请求也可以直接传递 json 数据,在 post 请求中,可以自动将一个对象转换成 json 进行传输,数据到达 provider 之后,再被转换为一个对象。具体操作步骤如下:

  1. String url = "http://" + host + ":" + port + "/user";
  2. User u1 = new User();
  3. u1.setUsername("李四");
  4. u1.setAddress("深圳");
  5. ResponseEntity<User> responseEntity = restTemplate.postForEntity(url, u1, User.class);
  6. return responseEntity.getBody();

唯一的区别就是第二个参数的类型不同,这个参数如果是一个 MultiValueMap 的实例,则以 key/value 的形式发送,如果是一个普通对象,则会被转成 json 发送。

postForObject

postForObject 和 postForEntity 基本一致,就是返回类型不同而已

postForLocation

postForLocation 方法的返回值是一个 Uri 对象,因为 POST 请求一般用来添加数据,有的时候需要将刚刚添加成功的数据的 URL 返回来,此时就可以使用这个方法,一个常见的使用场景如用户注册功能,用户注册成功之后,可能就自动跳转到登录页面了,此时就可以使用该方法。

  1. String url = "http://" + host + ":" + port + "/register";
  2. MultiValueMap map = new LinkedMultiValueMap();
  3. map.add("username", "李四");
  4. map.add("address", "深圳");
  5. URI uri = restTemplate.postForLocation(url, map);
  6. String s = restTemplate.getForObject(uri, String.class);
  7. return s;

注意:postForLocation 方法返回的 Uri 实际上是指响应头的 Location 字段,所以,provider 中 register 接口的响应头必须要有 Location 字段(即请求的接口实际上是一个重定向的接口),否则 postForLocation 方法的返回值为null

PUT 请求

只要将 GET 请求和 POST 请求搞定了,接下来 PUT 请求就会容易很多了,PUT 请求本身方法也比较少,只有三个,如下:

20210310145056349.png

这三个重载的方法其参数其实和 POST 是一样的,可以用 key/value 的形式传参,也可以用 JSON 的形式传参,无论哪种方式,都是没有返回值的

  1. String host ="myhost";
  2. int port = "8080";
  3. String url1 = "http://" + host + ":" + port + "/user/name";
  4. String url2 = "http://" + host + ":" + port + "/user/address";
  5. MultiValueMap map = new LinkedMultiValueMap();
  6. map.add("username", "李四");
  7. map.add("address", "深圳");
  8. restTemplate.put(url1, map);
  9. User u1 = new User();
  10. u1.setAddress("广州");
  11. u1.setUsername("张三");
  12. restTemplate.put(url2, u1);

DELETE 请求

和 PUT 请求一样,DELETE 请求也是比较简单的,只有三个方法,如下:

20210310145628458.png

不同于 POST 和 PUT ,DELETE 请求的参数只能在地址栏传送,可以是直接放在路径中,也可以用 key/value 的形式传递,当然,这里也是没有返回值的。

  1. String host = "myhost";
  2. int port = "8080";
  3. String url1 = "http://" + host + ":" + port + "/user/{1}";
  4. String url2 = "http://" + host + ":" + port + "/user/?username={username}";
  5. Map<String,String> map = new HashMap<>();
  6. map.put("username", "李四");
  7. restTemplate.delete(url1, 99);
  8. restTemplate.delete(url2, map);

这里参数的传递和 GET 请求基本一致

通用方法 exchange

在 RestTemplate 中还有一个通用的方法 exchange。为什么说它通用呢?因为这个方法需要你在调用的时候去指定请求类型,即它既能做 GET 请求,也能做 POST 请求,也能做其它各种类型的请求。如果开发者需要对请求进行封装,使用它再合适不过了

  1. @GetMapping("/hello12")
  2. public void hello12() {
  3. List<ServiceInstance> list = discoveryClient.getInstances("provider");
  4. ServiceInstance instance = list.get(0);
  5. String host = instance.getHost();
  6. int port = instance.getPort();
  7. String url = "http://" + host + ":" + port + "/customheader";
  8. HttpHeaders headers = new HttpHeaders();
  9. headers.add("cookie","justdojava");
  10. HttpEntity<MultiValueMap<String,String>> request = new HttpEntity<>(null,headers);
  11. ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
  12. System.out.println(responseEntity.getBody());
  13. }

4、自定义设置

手动指定转换器(HttpMessageConverter)

我们知道,调用reseful接口传递的数据内容是json格式的字符串,返回的响应也是json格式的字符串。然而restTemplate.postForObject方法的请求参数RequestBean和返回参数ResponseBean却都是java类。是RestTemplate通过HttpMessageConverter自动帮我们做了转换的操作。

默认情况下RestTemplate自动帮我们注册了一组HttpMessageConverter用来处理一些不同的contentType的请求。
StringHttpMessageConverter来处理text/plain;MappingJackson2HttpMessageConverter来处理application/json;MappingJackson2XmlHttpMessageConverter来处理application/xml
你可以在org.springframework.http.converter包下找到所有spring帮我们实现好的转换器。
如果现有的转换器不能满足你的需求,你还可以实现org.springframework.http.converter.HttpMessageConverter接口自己写一个。详情参考官方api。

选好了HttpMessageConverter后怎么把它注册到我们的RestTemplate中呢。

  1. RestTemplate restTemplate = new RestTemplate();
  2. //获取RestTemplate默认配置好的所有转换器
  3. List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
  4. //默认的MappingJackson2HttpMessageConverter在第7个 先把它移除掉
  5. messageConverters.remove(6);
  6. //添加上GSON的转换器
  7. messageConverters.add(6, new GsonHttpMessageConverter());

这个简单的例子展示了如何使用GsonHttpMessageConverter替换掉默认用来处理application/jsonMappingJackson2HttpMessageConverter

设置底层连接方式

要创建一个RestTemplate的实例,您可以像上述例子中简单地调用默认的无参数构造函数。这将使用java.net包中的标准Java类作为底层实现来创建HTTP请求。
但很多时候我们需要像传统的HttpClient那样设置HTTP请求的一些属性。RestTemplate使用了一种很偷懒的方式实现了这个需求,那就是直接使用一个HttpClient作为底层实现……

  1. //生成一个设置了连接超时时间、请求超时时间、异常最大重试次数的httpClient
  2. RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(30000).build();
  3. HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config).setRetryHandler(new DefaultHttpRequestRetryHandler(5, false));
  4. HttpClient httpClient = builder.build();
  5. //使用httpClient创建一个ClientHttpRequestFactory的实现
  6. ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
  7. //ClientHttpRequestFactory作为参数构造一个使用作为底层的RestTemplate
  8. RestTemplate restTemplate = new RestTemplate(requestFactory);

设置拦截器(ClientHttpRequestInterceptor)

有时候我们需要对请求做一些通用的拦截设置,这就可以使用拦截器进行处理。拦截器需要我们实现org.springframework.http.client.ClientHttpRequestInterceptor接口自己写。

举个简单的例子,写一个在header中根据请求内容和地址添加令牌的拦截器。

  1. public class TokenInterceptor implements ClientHttpRequestInterceptor
  2. {
  3. @Override
  4. public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
  5. {
  6. //请求地址
  7. String checkTokenUrl = request.getURI().getPath();
  8. //token有效时间
  9. int ttTime = (int) (System.currentTimeMillis() / 1000 + 1800);
  10. //请求方法名 POST、GET等
  11. String methodName = request.getMethod().name();
  12. //请求内容
  13. String requestBody = new String(body);
  14. //生成令牌 此处调用一个自己写的方法,有兴趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程无关,就不贴出来了
  15. String token = TokenHelper.generateToken(checkTokenUrl, ttTime, methodName, requestBody);
  16. //将令牌放入请求header中
  17. request.getHeaders().add("X-Auth-Token",token);
  18. return execution.execute(request, body);
  19. }
  20. }

创建RestTemplate实例的时候可以这样向其中添加拦截器

  1. RestTemplate restTemplate = new RestTemplate();
  2. //向restTemplate中添加自定义的拦截器
  3. restTemplate.getInterceptors().add(new TokenInterceptor());

设置请求头

有的时候我们会有一些特殊的需求,例如模拟 cookie ,此时就需要我们自定义请求头了。自定义请求头可以通过拦截器的方式来实现(下篇文章我们会详细的说这个拦截器)。定义拦截器、自动修改请求数据、一些身份认证信息等,都可以在拦截器中来统一处理。具体操作步骤如下:

首先在 provider 中定义一个接口,在接口中获取客户端传来的 cookie 数据,如下:

  1. @GetMapping("/customheader")
  2. public String customHeader(HttpServletRequest req) {
  3. return req.getHeader("cookie");
  4. }

这里简单处理,将客户端传来的 cookie 拿出来后再返回给客户端,然后在 consumer 中添加如下接口来测试:

  1. @GetMapping("/hello11")
  2. public void hello11() {
  3. List<ServiceInstance> list = discoveryClient.getInstances("provider");
  4. ServiceInstance instance = list.get(0);
  5. String host = instance.getHost();
  6. int port = instance.getPort();
  7. String url = "http://" + host + ":" + port + "/customheader";
  8. restTemplate.setInterceptors(Collections.singletonList(new ClientHttpRequestInterceptor() {
  9. @Override
  10. public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
  11. HttpHeaders headers = request.getHeaders();
  12. headers.add("cookie","justdojava");
  13. return execution.execute(request,body);
  14. }
  15. }));
  16. String s = restTemplate.getForObject(url, String.class);
  17. System.out.println(s);
  18. }

这里通过调用 RestTemplate 的 setInterceptors 方法来给它设置拦截器,拦截器也可以有多个,我这里只有一个。在拦截器中,将请求拿出来,给它设置 cookie ,然后调用 execute 方法让请求继续执行。此时,在 /customheader 接口中,就能获取到 cookie了。

发表评论

表情:
评论列表 (有 0 条评论,816人围观)

还没有评论,来说两句吧...

相关阅读

    相关 axios+promise整合http请求

    前言 当以前后端分离的方式进行项目的开发时,我们可以简单地把前端开发看做页面展示的开发,把后端开发看做数据处理的开发。前端页面的展示,会根据需求去后端请求相应的数据。