本文介绍: 在本教程中,我们将学习如何使用Spring Boot和Apache HttpClient创建一个REST客户端。我们将探讨如何与远程服务器进行通信、处理JSON响应,并为Web应用程序配置跨源资源共享(CORS)。让我们深入代码吧!

使用Spring Boot和Apache HttpClient构建REST客户端

介绍:
在本文中,我们将学习如何使用Spring Boot和Apache HttpClient创建一个REST客户端。我们将探讨如何与远程服务器进行通信、处理JSON响应,并为Web应用程序配置跨源资源共享(CORS)。让我们深入代码吧!


服务层

ClientService 类负责发起HTTP请求并处理响应。它使用 @Service 注解表示它应该由Spring容器进行管理。

@Service
public class ClientService {
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private ObjectMapper objectMapper;
    
    // 发起GET请求并将响应作为Map返回的方法
    public Map ResponseMap(String url) throws IOException {
        // 创建GET请求,并使用提供的URL
        HttpGet request = new HttpGet(url);

        // 发送请求并获取响应
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();

        // 处理响应体
        Map responseBody = null;
        if (entity != null) {
            String jsonString = EntityUtils.toString(entity);
            responseBody = objectMapper.readValue(jsonString, Map.class);
        }

        // 关闭连接
        EntityUtils.consume(entity);

        return responseBody;
    }

    // 发起GET请求并将响应作为String返回的方法
    public String ResponString(String url) throws IOException {
        // 创建GET请求,并使用提供的URL
        HttpGet request = new HttpGet(url);

        // 发送请求并获取响应
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();

        // 处理响应体
        String responseBody = "";
        if (entity != null) {
            responseBody = EntityUtils.toString(entity);
        }

        // 关闭连接
        EntityUtils.consume(entity);

        return responseBody;
    }
}

控制器层

MyClientController 类是控制器层,负责处理HTTP请求并返回响应。

@RestController
@RequestMapping("/api")
public class MyClientController {
    private final ObjectMapper objectMapper;
    private final CloseableHttpClient httpClient;
    private final ClientService clientService;

    @Autowired
    public MyClientController(CloseableHttpClient httpClient, ObjectMapper objectMapper, ClientService clientService) {
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
        this.clientService = clientService;
    }

    @GetMapping("/example")
    public ResponseEntity<String> ResponString() throws IOException {
        String s = clientService.ResponString("http://localhost:8081/api/test");
        return ResponseEntity.ok(s);
    }

    @GetMapping("/mapreq")
    public ResponseEntity<Map> ResponseMap() throws IOException {
        Map map1 = clientService.ResponseMap("http://localhost:8081/flux/testmap");
        System.out.println("map1 = " + map1);
        Object key1 = map1.get("key1");
        System.out.println("key1.toString() = " + key1.toString());
        return ResponseEntity.ok(map1);
    }

    @GetMapping("/test")
    public String testEndpoint() {
        return "test";
    }
}

配置类

HttpClientConfiguration 类是一个配置类,用于自动装配到Bean中。

@Configuration
public class HttpClientConfiguration {

    @Bean
    public CloseableHttpClient httpClient() {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        // 设置请求头
        httpClientBuilder.setDefaultHeaders(Arrays.asList(createDefaultHeaders()));

        // 设置基础配置
        httpClientBuilder.setDefaultRequestConfig(createRequestConfig());

        // 创建HttpClient对象
        CloseableHttpClient httpClient = httpClientBuilder.build();
        return httpClient;
    }

    private RequestConfig createRequestConfig() {
        // 设置连接超时时间
        int connectionTimeout = 5000;
        // 设置读取超时时间
        int socketTimeout = 5000;

        return RequestConfig.custom()
                .setConnectTimeout(connectionTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
    }

    private Header[] createDefaultHeaders() {
        Header[] headers = {
                new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
                // 可以添加其他请求头
        };
        return headers;
    }
}

跨域配置

MyCorsConfiguration 类是一个配置类,用于配置WebFlux的跨域。

@Configuration
public class MyCorsConfiguration extends org.springframework.web.cors.CorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.addAllowedOrigin("*");
        corsConfig.addAllowedMethod("*");
        corsConfig.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }
}

在本示例中,我们创建了一个包含服务层、控制器层和配置类的Spring Boot应用程序。服务层的 ClientService 类负责通过Apache HttpClient发起HTTP请求,并处理响应。控制器层的 MyClientController 类负责处理HTTP请求并返回响应。我们还创建了一个配置类 HttpClientConfiguration,用于配置Apache HttpClient,并将其作为Bean注入到应用程序中。另外,我们还创建了一个配置类 MyCorsConfiguration,用于配置WebFlux的跨域资源共享(CORS)。

Spring Boot和Apache HttpClient构建REST客户端的应用。

  1. 错误处理:在实际应用中,处理HTTP请求和响应中的错误非常重要。您可以在ClientService类中添加适当的错误处理机制,例如处理连接超时、读取超时、状态码错误等。这样可以提高应用程序的健壮性和容错性。

  2. 请求参数和请求体:在实际场景中,您可能需要向服务器发送具有请求参数或请求体的HTTP请求。您可以使用HttpClient的不同方法(例如HttpPost)来发送包含请求参数或请求体的POST请求。在ClientService类中添加相应的方法来处理这些类型的请求。

  3. 身份验证和授权:如果您需要对HTTP请求进行身份验证或授权,您可以使用Apache HttpClient提供的功能来处理这些方面。例如,您可以设置请求头中的身份验证凭据,或者使用OAuth等授权机制来访问受限资源。

  4. 并发请求:在某些情况下,您可能需要同时发起多个HTTP请求,并在所有请求完成后进行处理。您可以使用Apache HttpClient的异步功能或结合Spring Boot的异步支持来实现并发请求。

  5. 单元测试:编写单元测试对于确保REST客户端的正确性和稳定性非常重要。您可以使用Spring Boot提供的测试框架(如JUnit和MockMvc)来编写单元测试,并模拟HTTP请求和响应。

  6. 日志记录:在开发和调试过程中,记录HTTP请求和响应的详细信息非常有用。您可以使用适当的日志记录框架(如Logback或Log4j)来记录HTTP请求和响应的信息,以便进行故障排除和性能优化。

原文地址:https://blog.csdn.net/m0_68856746/article/details/135545404

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_55812.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注