• 基于Spring Boot使用Java调用http请求的6种方式


    记录:287

    场景:基于Spring Boot使用Java调用http请求的6种方式。服务端发布一个POST请求和2个GET请求。使用6种方式实现的客户端都调用服务端发布的这3个方法。可以直观感受和比对6种http请求的客户端。

    版本:

    1. Spring Boot 2.6.3
    2. Spring Framework 5.3.15
    3. Spring Cloud 2021.0.1

    一、案例场景

    本例实现6种方式客户端调用同一个服务端的3种方法。

    1.服务端

    在服务端发布一个POST请求,2个GET请求。

    1.1 接口信息

    (1)POST请求

    1. [访问URL]: http://127.0.0.1:19091/server/comm/f1
    2. [请求方式]: POST
    3. [请求参数]: JSON
    4. {"userName":"HangZhou20220719","tradeName":"Vue进阶教程"}
    5. [返回值]: JSON
    6. {code=200, message=成功}

    (2)GET请求(一)

    1. [访问URL]: http://127.0.0.1:19091/server/comm/f2
    2. [请求方式]: GET
    3. [请求参数]: String
    4. obj=HangZhou20220719
    5. [返回值]: JSON
    6. {code=200, message=成功}

    (3)GET请求(二)

    1. [访问URL]: http://127.0.0.1:19091/server/comm/f3/{obj}
    2. [请求方式]: GET
    3. [请求参数]: String
    4. obj=HangZhou20220719
    5. [返回值]: JSON
    6. {code=200, message=成功}

    1.2 服务端代码

    服务端3个接口代码。

    1. @Slf4j
    2. @RestController
    3. @RequestMapping("/comm")
    4. public class CommonController {
    5. /**
    6. * 1.发布POST请求
    7. * 入参注解: @RequestBody
    8. * 返回注解: @ResponseBody(@RestController包含此注解)
    9. * */
    10. @PostMapping("/f1")
    11. public Object f1(@RequestBody Object obj) {
    12. log.info("CommonController->f1,接收参数,obj = " + obj.toString());
    13. log.info("CommonController->f1,处理业务.");
    14. log.info("CommonController->f1,返回.");
    15. return ResultObj.builder().code("200").message("成功").build();
    16. }
    17. /**
    18. * 2.发布GET请求
    19. * 入参注解: @RequestParam
    20. * 返回注解: @ResponseBody(@RestController包含此注解)
    21. * */
    22. @GetMapping ("/f2")
    23. public Object f2(@RequestParam("obj") String obj) {
    24. log.info("CommonController->f2,接收参数,obj = " + obj.toString());
    25. log.info("CommonController->f2,处理业务.");
    26. log.info("CommonController->f2,返回.");
    27. return ResultObj.builder().code("200").message("成功").build();
    28. }
    29. /**
    30. * 3.发布GET请求
    31. * 入参注解: @PathVariable
    32. * 返回注解: @ResponseBody(@RestController包含此注解)
    33. * */
    34. @GetMapping ("/f3/{obj}")
    35. public Object f3(@PathVariable("obj") String obj) {
    36. log.info("CommonController->f3,接收参数,obj = " + obj.toString());
    37. log.info("CommonController->f3,处理业务.");
    38. log.info("CommonController->f3,返回.");
    39. return ResultObj.builder().code("200").message("成功").build();
    40. }
    41. }

    1.3 服务端辅助对象

    服务端辅助对象。

    1. @Data
    2. @NoArgsConstructor
    3. @AllArgsConstructor
    4. @Builder
    5. public class ResultObj {
    6. private String code;
    7. private String message;
    8. }

    二、Java调用http请求的6种方式

    1.使用HttpURLConnection调用http请求

    (1)Jar包位置

    HttpURLConnection,全称:java.net.HttpURLConnection。

    JDK 1.8中自带的rt.jar包中的java.net包内的类。

    (2)客户端代码

    1. public class Utils01JdkClient {
    2. public static void main(String[] args) throws Exception {
    3. f1();
    4. f2();
    5. f3();
    6. }
    7. /**
    8. * 1.使用HttpURLConnection调用服务端的POST请求
    9. * 服务端入参注解: @RequestBody
    10. */
    11. public static void f1() throws Exception {
    12. // 1.请求URL
    13. String postUrl = "http://127.0.0.1:19091/server/comm/f1";
    14. // 2.请求参数JSON格式
    15. Map map = new HashMap<>();
    16. map.put("userName", "HangZhou20220718");
    17. map.put("tradeName", "Vue进阶教程");
    18. String json = JSON.toJSONString(map);
    19. // 3.创建连接与设置连接参数
    20. URL urlObj = new URL(postUrl);
    21. HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
    22. httpConn.setRequestMethod("POST");
    23. httpConn.setRequestProperty("Charset", "UTF-8");
    24. // POST请求且JSON数据,必须设置
    25. httpConn.setRequestProperty("Content-Type", "application/json");
    26. // 打开输出流,默认是false
    27. httpConn.setDoOutput(true);
    28. // 打开输入流,默认是true,可省略
    29. httpConn.setDoInput(true);
    30. // 4.从HttpURLConnection获取输出流和写数据
    31. OutputStream oStream = httpConn.getOutputStream();
    32. oStream.write(json.getBytes());
    33. oStream.flush();
    34. // 5.发起http调用(getInputStream触发http请求)
    35. if (httpConn.getResponseCode() != 200) {
    36. throw new Exception("调用服务端异常.");
    37. }
    38. // 6.从HttpURLConnection获取输入流和读数据
    39. BufferedReader br = new BufferedReader(
    40. new InputStreamReader(httpConn.getInputStream()));
    41. String resultData = br.readLine();
    42. System.out.println("从服务端返回结果: " + resultData);
    43. // 7.关闭HttpURLConnection连接
    44. httpConn.disconnect();
    45. }
    46. /**
    47. * 2.使用HttpURLConnection调用服务端的GET请求
    48. * 服务端入参注解: @RequestParam
    49. */
    50. public static void f2() throws Exception {
    51. // 1.请求URL与组装请求参数
    52. String getUrl = "http://127.0.0.1:19091/server/comm/f2";
    53. String obj = "Vue进阶教程";
    54. String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
    55. getUrl = getUrl + para;
    56. // 2.创建连接与设置连接参数
    57. URL urlObj = new URL(getUrl);
    58. HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
    59. httpConn.setRequestMethod("GET");
    60. httpConn.setRequestProperty("Charset", "UTF-8");
    61. // 3.发起http调用(getInputStream触发http请求)
    62. if (httpConn.getResponseCode() != 200) {
    63. throw new Exception("调用服务端异常.");
    64. }
    65. // 4.从HttpURLConnection获取输入流和读数据
    66. BufferedReader br = new BufferedReader(
    67. new InputStreamReader(httpConn.getInputStream()));
    68. String resultData = br.readLine();
    69. System.out.println("从服务端返回结果: " + resultData);
    70. // 5.关闭HttpURLConnection连接
    71. httpConn.disconnect();
    72. }
    73. /**
    74. * 3.使用HttpURLConnection调用服务端的GET请求
    75. * 服务端入参注解: @PathVariable
    76. */
    77. public static void f3() throws Exception {
    78. // 1.请求URL与组装请求参数
    79. String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
    80. String obj = "Vue进阶教程";
    81. obj = URLEncoder.encode(obj, "UTF-8");
    82. getUrl = getUrl + obj;
    83. URL urlObj = new URL(getUrl);
    84. // 2.创建连接与设置连接参数
    85. HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
    86. httpConn.setRequestMethod("GET");
    87. httpConn.setRequestProperty("charset", "UTF-8");
    88. // 3.发起http调用(getInputStream触发http请求)
    89. if (httpConn.getResponseCode() != 200) {
    90. throw new Exception("调用服务端异常.");
    91. }
    92. // 4.从HttpURLConnection获取输入流和读数据
    93. BufferedReader br = new BufferedReader(
    94. new InputStreamReader(httpConn.getInputStream()));
    95. String resultData = br.readLine();
    96. System.out.println("从服务端返回结果: " + resultData);
    97. // 5.关闭HttpURLConnection连接
    98. httpConn.disconnect();
    99. }
    100. }

    2.使用commons-httpclient调用http请求

    (1)Jar包位置

    commons-httpclient,比较早的Jar包,在MVNRepository仓库中,查看的最新维护时间是:2007年8月。

    1. <dependency>
    2. <groupId>commons-httpclientgroupId>
    3. <artifactId>commons-httpclientartifactId>
    4. <version>3.1version>
    5. dependency>

    (2)客户端代码

    1. public class Utils02CommonsHttpClient {
    2. public static void main(String[] args) throws Exception {
    3. f1();
    4. f2();
    5. f3();
    6. }
    7. /**
    8. * 1.使用commons-httpclient调用服务端的POST请求
    9. * 服务端入参注解: @RequestBody
    10. */
    11. public static void f1() throws Exception {
    12. // 1.请求URL
    13. String postUrl = "http://127.0.0.1:19091/server/comm/f1";
    14. // 2.请求参数
    15. Map map = new HashMap<>();
    16. map.put("userName", "HangZhou20220718");
    17. map.put("tradeName", "Vue进阶教程");
    18. String json = JSON.toJSONString(map);
    19. // 3.创建连接与设置连接参数
    20. HttpClient httpClient = new HttpClient();
    21. PostMethod postMethod = new PostMethod(postUrl);
    22. postMethod.addRequestHeader("Content-Type", "application/json");
    23. RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
    24. postMethod.setRequestEntity(entity);
    25. //解决返回值中文乱码
    26. postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    27. String resultData = "";
    28. // 4.发起请求
    29. int code = httpClient.executeMethod(postMethod);
    30. if (code != 200) {
    31. throw new Exception("调用服务端异常.");
    32. }
    33. // 5.接收返回值
    34. resultData = postMethod.getResponseBodyAsString();
    35. System.out.println("从服务端返回结果: " + resultData);
    36. // 6.关闭连接
    37. postMethod.releaseConnection();
    38. }
    39. /**
    40. * 2.使用commons-httpclient调用服务端的GET请求
    41. * 服务端入参注解: @RequestParam
    42. */
    43. public static void f2() throws Exception {
    44. // 1.请求URL与组装请求参数
    45. String getUrl = "http://127.0.0.1:19091/server/comm/f2";
    46. String obj = "Vue进阶教程";
    47. //入参有中文需要编码
    48. String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
    49. getUrl = getUrl + para;
    50. // 2.创建连接与设置连接参数
    51. HttpClient httpClient = new HttpClient();
    52. GetMethod getMethod = new GetMethod(getUrl);
    53. //解决返回值中文乱码
    54. getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    55. // 3.发起请求
    56. int code = httpClient.executeMethod(getMethod);
    57. String resultData = "";
    58. if (code != 200) {
    59. throw new Exception("调用服务端异常.");
    60. }
    61. // 4.接收返回值
    62. resultData = getMethod.getResponseBodyAsString();
    63. System.out.println("从服务端返回结果: " + resultData);
    64. // 5.关闭连接
    65. getMethod.releaseConnection();
    66. }
    67. /**
    68. * 3.使用commons-httpclient调用服务端的GET请求
    69. * 服务端入参注解: @PathVariable
    70. */
    71. public static void f3() throws Exception {
    72. // 1.请求URL与组装请求参数
    73. String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
    74. String obj = "Vue进阶教程";
    75. //入参有中文需要编码
    76. obj = URLEncoder.encode(obj, "UTF-8");
    77. getUrl = getUrl + obj;
    78. // 2.创建连接与设置连接参数
    79. HttpClient httpClient = new HttpClient();
    80. GetMethod getMethod = new GetMethod(getUrl);
    81. //解决返回值中文乱码
    82. getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    83. // 3.发起请求
    84. int code = httpClient.executeMethod(getMethod);
    85. String resultData = "";
    86. if (code != 200) {
    87. throw new Exception("调用服务端异常.");
    88. }
    89. // 4.接收返回值
    90. resultData = getMethod.getResponseBodyAsString();
    91. System.out.println("从服务端返回结果: " + resultData);
    92. // 5.关闭连接
    93. getMethod.releaseConnection();
    94. }
    95. }

    3.使用org.apache.httpcomponents调用http请求

    (1)Jar包位置

    httpcomponents,在MVNRepository仓库中,查看的最新维护时间是:2020年10月。

    1. <dependency>
    2. <groupId>org.apache.httpcomponentsgroupId>
    3. <artifactId>httpclientartifactId>
    4. <version>4.5.13version>
    5. dependency>

    (2)客户端代码

    1. public class Utils03HttpComponentsClient {
    2. public static void main(String[] args) throws Exception {
    3. f1();
    4. f2();
    5. f3();
    6. }
    7. /**
    8. * 1.使用org.apache.httpcomponents调用服务端的POST请求
    9. * 服务端入参注解: @RequestBody
    10. */
    11. public static void f1() throws Exception {
    12. // 1.请求URL
    13. String postUrl = "http://127.0.0.1:19091/server/comm/f1";
    14. // 2.请求参数
    15. Map map = new HashMap<>();
    16. map.put("userName", "HangZhou20220718");
    17. map.put("tradeName", "Vue进阶教程");
    18. String json = JSON.toJSONString(map);
    19. // 3.创建连接与设置连接参数
    20. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    21. HttpPost httpPost = new HttpPost(postUrl);
    22. StringEntity entity = new StringEntity(json);
    23. entity.setContentEncoding("UTF-8");
    24. entity.setContentType("application/json");
    25. httpPost.setEntity(entity);
    26. // 4.发起请求与接收返回值
    27. HttpResponse response = httpClient.execute(httpPost);
    28. if (response.getStatusLine().getStatusCode() != 200) {
    29. throw new Exception("调用服务端异常.");
    30. }
    31. HttpEntity res = response.getEntity();
    32. String resultData = EntityUtils.toString(res);
    33. System.out.println("从服务端返回结果: " + resultData);
    34. // 5.关闭连接
    35. httpClient.close();
    36. }
    37. /**
    38. * 2.使用org.apache.httpcomponents调用服务端的GET请求
    39. * 服务端入参注解: @RequestParam
    40. */
    41. public static void f2() throws Exception {
    42. // 1.请求URL与组装请求参数
    43. String getUrl = "http://127.0.0.1:19091/server/comm/f2";
    44. String obj = "Vue进阶教程";
    45. String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
    46. getUrl = getUrl + para;
    47. // 2.创建连接与设置连接参数
    48. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    49. HttpGet httpGet = new HttpGet(getUrl);
    50. // 3.发起请求与接收返回值
    51. HttpResponse response = httpClient.execute(httpGet);
    52. if (response.getStatusLine().getStatusCode() != 200) {
    53. throw new Exception("调用服务端异常.");
    54. }
    55. HttpEntity res = response.getEntity();
    56. String resultData = EntityUtils.toString(res);
    57. System.out.println("从服务端返回结果: " + resultData);
    58. // 4.关闭连接
    59. httpClient.close();
    60. }
    61. /**
    62. * 3.使用org.apache.httpcomponents调用服务端的GET请求
    63. * 服务端入参注解: @PathVariable
    64. */
    65. public static void f3() throws Exception {
    66. // 1.请求URL与组装请求参数
    67. String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
    68. String obj = "Vue进阶教程";
    69. //入参有中文需要编码
    70. obj = URLEncoder.encode(obj, "UTF-8");
    71. getUrl = getUrl + obj;
    72. // 2.创建连接与设置连接参数
    73. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    74. HttpGet httpGet = new HttpGet(getUrl);
    75. // 3.发起请求与接收返回值
    76. HttpResponse response = httpClient.execute(httpGet);
    77. if (response.getStatusLine().getStatusCode() != 200) {
    78. throw new Exception("调用服务端异常.");
    79. }
    80. HttpEntity res = response.getEntity();
    81. String resultData = EntityUtils.toString(res);
    82. System.out.println("从服务端返回结果: " + resultData);
    83. // 4.关闭连接
    84. httpClient.close();
    85. }
    86. }

    4.使用OkHttp调用http请求

    (1)Jar包位置

    com.squareup.okhttp3,本例使用版本。

    1. <dependency>
    2. <groupId>com.squareup.okhttp3groupId>
    3. <artifactId>okhttpartifactId>
    4. <version>4.10.0version>
    5. <exclusions>
    6. <exclusion>
    7. <groupId>com.google.androidgroupId>
    8. <artifactId>androidartifactId>
    9. exclusion>
    10. exclusions>
    11. dependency>

    (2)客户端代码

    1. public class Utils04OkHttpClient {
    2. public static void main(String[] args) throws Exception {
    3. f1();
    4. f2();
    5. f3();
    6. }
    7. /**
    8. * 1.使用okhttp调用服务端的POST请求
    9. * 服务端入参注解: @RequestBody
    10. * */
    11. public static void f1() throws Exception {
    12. // 1.请求URL
    13. String postUrl = "http://127.0.0.1:19091/server/comm/f1";
    14. // 2.请求参数
    15. Map map = new HashMap<>();
    16. map.put("userName", "HangZhou20220718");
    17. map.put("tradeName", "Vue进阶教程");
    18. String json = JSON.toJSONString(map);
    19. // 3.创建连接与设置连接参数
    20. MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
    21. RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
    22. Request request = new Request.Builder().url(postUrl).post(requestBody).build();
    23. OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    24. // 4.发起请求与接收返回值
    25. Response response = okHttpClient.newCall(request).execute();
    26. String resultData = response.body().string();
    27. System.out.println("从服务端返回结果: " + resultData);
    28. }
    29. /**
    30. * 2.使用okhttp调用服务端的GET请求
    31. * 服务端入参注解: @RequestParam
    32. * */
    33. public static void f2() throws Exception {
    34. // 1.请求URL与组装请求参数
    35. String getUrl = "http://127.0.0.1:19091/server/comm/f2";
    36. String obj = "Vue进阶教程";
    37. String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
    38. getUrl = getUrl + para;
    39. // 2.创建连接与设置连接参数
    40. Request request = new Request.Builder().url(getUrl).build();
    41. OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    42. // 3.发起请求与接收返回值
    43. Response response = okHttpClient.newCall(request).execute();
    44. String resultData = response.body().string();
    45. System.out.println("从服务端返回结果: " + resultData);
    46. }
    47. /**
    48. * 3.使用okhttp调用服务端的GET请求
    49. * 服务端入参注解: @PathVariable
    50. * */
    51. public static void f3() throws Exception {
    52. // 1.请求URL与组装请求参数
    53. String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
    54. String obj = "Vue进阶教程";
    55. obj = URLEncoder.encode(obj, "UTF-8");
    56. getUrl = getUrl + obj;
    57. // 2.创建连接与设置连接参数
    58. Request request = new Request.Builder().url(getUrl).build();
    59. OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    60. // 3.发起请求与接收返回值
    61. Response response = okHttpClient.newCall(request).execute();
    62. String resultData = response.body().string();
    63. System.out.println("从服务端返回结果: " + resultData);
    64. }
    65. }

    5.使用RestTemplate调用http请求

    (1)Jar包位置

    RestTemplate,全称org.springframework.web.client.RestTemplate。

    本例使用版本。

    1. dependency>
    2. <groupId>org.springframeworkgroupId>
    3. <artifactId>spring-webartifactId>
    4. <version>5.3.15version>
    5. <scope>compilescope>
    6. dependency>

    (2)客户端代码

    1. public class Utils05RestTemplateClient {
    2. public static void main(String[] args) throws Exception {
    3. f1();
    4. f2();
    5. f3();
    6. }
    7. /**
    8. * 1.使用RestTemplate调用服务端的POST请求
    9. * 服务端入参注解: @RequestBody
    10. */
    11. public static void f1() throws Exception {
    12. // 1.请求URL
    13. String postUrl = "http://127.0.0.1:19091/server/comm/f1";
    14. // 2.请求参数JSON格式
    15. Map map = new HashMap<>();
    16. map.put("userName", "HangZhou20220718");
    17. map.put("tradeName", "Vue进阶教程");
    18. String json = JSON.toJSONString(map);
    19. // 3.创建RestTemplate
    20. RestTemplate restTemplate = new RestTemplate();
    21. // 4.设置RestTemplate参数(请求头和body)
    22. HttpHeaders headers = new HttpHeaders();
    23. MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
    24. headers.setContentType(mediaType);
    25. headers.add("Accept", "application/json");
    26. HttpEntity entity = new HttpEntity<>(json, headers);
    27. // 5.使用RestTemplate发起请求与接收返回值
    28. String resultData = restTemplate.postForObject(postUrl, entity, String.class);
    29. System.out.println("从服务端返回结果: " + resultData);
    30. }
    31. /**
    32. * 2.使用RestTemplate调用服务端的GET请求
    33. * 服务端入参注解: @RequestParam
    34. */
    35. public static void f2() throws Exception {
    36. // 1.请求URL与组装请求参数
    37. String getUrl = "http://127.0.0.1:19091/server/comm/f2";
    38. String obj = "Vue进阶教程";
    39. String para = "?obj=" + obj;
    40. getUrl = getUrl + para;
    41. // 2.创建RestTemplate
    42. RestTemplate restTemplate = new RestTemplate();
    43. // 3.使用RestTemplate发起请求与接收返回值
    44. String resultData = restTemplate.getForObject(getUrl, String.class);
    45. System.out.println("从服务端返回结果: " + resultData);
    46. }
    47. /**
    48. * 3.使用RestTemplate调用服务端的GET请求
    49. * 服务端入参注解: @PathVariable
    50. */
    51. public static void f3() throws Exception {
    52. // 1.请求URL与组装请求参数
    53. String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
    54. String obj = "Vue进阶教程";
    55. getUrl = getUrl + obj;
    56. // 2.创建RestTemplate
    57. RestTemplate restTemplate = new RestTemplate();
    58. // 3.使用RestTemplate发起请求与接收返回值
    59. String resultData = restTemplate.getForObject(getUrl, String.class);
    60. System.out.println("从服务端返回结果: " + resultData);
    61. }
    62. }

    6.使用OpenFeign调用http请求

    (1)Jar包位置

    Spring Cloud OpenFeign是Spring Cloud全家桶组件成员。

    本例版本:Spring Cloud 2021.0.1;spring-cloud-openfeign 3.1.1

    1. <dependency>
    2. <groupId>org.springframework.cloudgroupId>
    3. <artifactId>spring-cloud-starter-openfeignartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>org.springframework.cloudgroupId>
    7. <artifactId>spring-cloud-starter-loadbalancerartifactId>
    8. dependency>

    (2)客户端代码(Feign接口)

    1. @FeignClient(contextId = "utils06OpenFeign",
    2. value = "example-server")
    3. public interface Utils06OpenFeignClient {
    4. /**
    5. * 1.使用openfeign调用服务端的POST请求
    6. * 服务端入参注解: @RequestBody
    7. * */
    8. @ResponseBody
    9. @PostMapping("/server/comm/f1")
    10. Object f1(@RequestBody Object obj);
    11. /**
    12. * 2.使用openfeign调用服务端的GET请求
    13. * 服务端入参注解: @RequestParam
    14. * */
    15. @ResponseBody
    16. @GetMapping("/server/comm/f2")
    17. Object f2(@RequestParam("obj") String obj);
    18. /**
    19. * 3.使用openfeign调用服务端的GET请求
    20. * 服务端入参注解: @PathVariable
    21. * */
    22. @ResponseBody
    23. @GetMapping("/server/comm/f3/{obj}")
    24. Object f3(@PathVariable("obj") String obj);
    25. }

    (3)客户端代码(调用Feign接口)

    1. /**
    2. * 触发请求:
    3. * http://127.0.0.1:19092/client/exam/f
    4. * */
    5. @Slf4j
    6. @RestController
    7. @RequestMapping("/exam")
    8. public class ExampleController {
    9. /**
    10. * 1.注入Feign接口
    11. * */
    12. @Autowired
    13. private Utils06OpenFeignClient feignClient;
    14. /**
    15. * 2.调用Feign接口
    16. * */
    17. @GetMapping("/f")
    18. public void f() throws Exception {
    19. log.info("使用Feign调用服务端f1: ");
    20. Map map = new HashMap<>();
    21. map.put("userName", "HangZhou20220718");
    22. map.put("tradeName", "Vue进阶教程");
    23. Object resultDataF1 = feignClient.f1(map);
    24. log.info("使用Feign调用服务端f1,返回结果: " + resultDataF1);
    25. log.info("使用Feign调用服务端f2: ");
    26. String obj = "Vue进阶教程";
    27. Object resultDataF2 = feignClient.f2(obj);
    28. log.info("使用Feign调用服务端f2,返回结果: " + resultDataF2);
    29. log.info("使用Feign调用服务端f3: ");
    30. String obj2 = "Vue进阶教程";
    31. Object resultDataF3 = feignClient.f3(obj2);
    32. log.info("使用Feign调用服务端f3,返回结果: " + resultDataF3);
    33. }
    34. }

    (4)本例使用基础

    Spring Cloud OpenFeign是Spring Cloud 组件,搭建的微服务都是基于Spring Cloud架构。本例两个微服务:

    服务端:example-server

    客户端:example-feign-client

    服务端和客户端都使用Nacos作为服务注册和发现中心,在客户端example-feign-client中整合Spring Cloud OpenFeign,服务端不需要修改。在启动类中加@EnableFeignClients注解,在使用OpenFeign的接口上加@FeignClient注解。

    以上,感谢。

    2022年7月20日

  • 相关阅读:
    浅析vue的createApp方法
    Electron是什么以及可以做什么
    深度解析大模型代码能力现状
    算法4: LeetCode_K个节点的组内逆序调整
    互联网Java工程师面试题·Dubbo篇·第一弹
    python开发环境搭建——pycharm和jupyternotebook
    AdaVITS—基于VITS的小型化说话人自适应模型
    AtCoder Beginner Contest 279 G. At Most 2 Colors(计数/组合数学/dp递推)
    Nginx人门详解
    pinia 入门及使用
  • 原文地址:https://blog.csdn.net/zhangbeizhen18/article/details/125899199