`
rensanning
  • 浏览: 3552637 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:38217
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:607605
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:682783
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:89534
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:402150
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69760
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:91835
社区版块
存档分类
最新评论

Spring Boot 入门 - 进阶篇(4)- REST访问(RestTemplate)

 
阅读更多
经常需要发送一个GET/POST请求到其他系统(REST API),通过JDK自带的HttpURLConnection、Apache HttpClient、Netty 4、OkHTTP 2/3都可以实现。

HttpClient的使用:http://rensanning.iteye.com/blog/1550436

Spring的RestTemplate封装了这些库的实现,使用起来更简洁。

RestTemplate包含以下几个部分:
  • HttpMessageConverter 对象转换器
  • ClientHttpRequestFactory 默认是JDK的HttpURLConnection
  • ResponseErrorHandler 异常处理
  • ClientHttpRequestInterceptor 请求拦截器


@Service
public class AccountService {

    @Autowired
    private RestTemplate restTemplate;

    // ...

}


(1)发送GET请求(getForObject()、getForEntity()、exchange())

// 1-getForObject()
User user1 = this.restTemplate.getForObject(uri, User.class);

// 2-getForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.getForEntity(uri, User.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
User user2 = responseEntity1.getBody();

// 3-exchange()
RequestEntity requestEntity = RequestEntity.get(new URI(uri)).build();
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
User user3 = responseEntity2.getBody();


(2)发送POST请求(postForObject()、postForEntity()、exchange())

// 1-postForObject()
User user1 = this.restTemplate.postForObject(uri, user, User.class);

// 2-postForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class);

// 3-exchange()
RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);


(3)设置HTTP Header信息

// 1-Content-Type
RequestEntity<User> requestEntity = RequestEntity
        .post(new URI(uri))
        .contentType(MediaType.APPLICATION_JSON)
        .body(user);

// 2-Accept
RequestEntity<User> requestEntity = RequestEntity
        .post(new URI(uri))
        .accept(MediaType.APPLICATION_JSON)
        .body(user);

// 3-Other
RequestEntity<User> requestEntity = RequestEntity
        .post(new URI(uri))
        .header("Authorization", "Basic " + base64Credentials)
        .body(user);


(4)异常处理

捕获HttpServerErrorException

int retryCount = 0;
while (true) {
    try {
        responseEntity = restTemplate.exchange(requestEntity, String.class);
        break;
    } catch (HttpServerErrorException e) {
        if (retryCount == 3) {
            throw e;
        }
        retryCount++;
    }
}


自定义异常处理

public class CustomErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {

    }

}

@Configuration
public class RestClientConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new CustomErrorHandler());
        return restTemplate;
    }

}


(5)设置超时时间

@Configuration
public class RestClientConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(clientHttpRequestFactory());
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(2000);
        factory.setConnectTimeout(2000);
        return factory;
    }
}


(6)设置连接池

@Configuration
public class RestClientConfig {

  @Bean
  public ClientHttpRequestFactory httpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
  }

  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate(httpRequestFactory());
  }

  @Bean
  public HttpClient httpClient() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
		.register("http", PlainConnectionSocketFactory.getSocketFactory())
		.register("https", SSLConnectionSocketFactory.getSocketFactory())
		.build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    RequestConfig requestConfig = RequestConfig.custom()
		.setSocketTimeout(8000)
		.setConnectTimeout(8000)
		.setConnectionRequestTimeout(8000)
		.build();

    return HttpClientBuilder.create()
		.setDefaultRequestConfig(requestConfig)
		.setConnectionManager(connectionManager)
		.build();
  }

}


(7)发送文件

MultiValueMap<String, Object> multiPartBody = new LinkedMultiValueMap<>();
multiPartBody.add("file", new ClassPathResource("/tmp/user.txt"));
RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity
        .post(uri)
        .contentType(MediaType.MULTIPART_FORM_DATA)
        .body(multiPartBody);


(8)下载文件

// 小文件
RequestEntity requestEntity = RequestEntity.get(uri).build();
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(requestEntity, byte[].class);
byte[] downloadContent = responseEntity.getBody();

// 大文件
ResponseExtractor<ResponseEntity<File>> responseExtractor = new ResponseExtractor<ResponseEntity<File>>() {
    @Override
    public ResponseEntity<File> extractData(ClientHttpResponse response) throws IOException {
        File rcvFile = File.createTempFile("rcvFile", "zip");
        FileCopyUtils.copy(response.getBody(), new FileOutputStream(rcvFile));
        return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(rcvFile);
    }
};
File getFile = this.restTemplate.execute(targetUri, HttpMethod.GET, null, responseExtractor);


(9)Spring Boot的RestTemplateBuilder

全局设置
@Component
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
    @Override
    public void customize(RestTemplate restTemplate) {
        new RestTemplateBuilder()
                .detectRequestFactory(false)
                .basicAuthorization("username", "password")
                .uriTemplateHandler(new OkHttp3ClientHttpRequestFactory())
                .errorHandler(new CustomResponseErrorHandler())
                .configure(restTemplate);
    }
}


单独设置
@Service
public class MyRestClientService {

    private RestTemplate restTemplate;

    public MyRestClientService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder
            .basicAuthorization("username", "password")
            .setConnectTimeout(3000)
            .setReadTimeout(5000)
            .rootUri("http://api.example.com/")
            .errorHandler(new CustomResponseErrorHandler())
            .additionalMessageConverters(new CustomHttpMessageConverter())
            .uriTemplateHandler(new OkHttp3ClientHttpRequestFactory())
            .build();
    }

    public String site() {
        return this.restTemplate.getForObject("http://rensanning.iteye.com/", String.class);
    }

}


参考:
http://qiita.com/kazuki43zoo/items/7cf3c8ca4f6f2283cefb
http://terasolunaorg.github.io/guideline/5.1.0.RELEASE/ja/ArchitectureInDetail/RestClient.html
  • 大小: 152.1 KB
分享到:
评论

相关推荐

    spring-boot-starter-parent-1.5.13.RELEASE.zip

    标题 "spring-boot-starter-parent-1.5.13.RELEASE.zip" 提供的信息表明,这是一个与Spring Boot相关的压缩包,具体来说是Spring Boot的起步依赖(Starter Parent)的一个版本,版本号为1.5.13.RELEASE。Spring Boot...

    jasypt-spring-boot-starter 3.0.5依赖的pom及jar

    《深入解析jasypt-spring-boot-starter 3.0.5依赖的POM与JAR》 在Java开发领域,构建和管理依赖是至关重要的环节。jasypt-spring-boot-starter是一个流行的安全库,它允许开发者在Spring Boot应用中轻松地实现加密...

    activiti-spring-boot-starter-basic-6.0.0适配springboot2.1.2

    activiti-spring-boot-starter-basic-6.0.0适配springboot2.1.2

    mybatis-spring-boot-starter-2.1.3.jar

    mybatis-spring-boot-starter-2.1.3.jarmybatis-spring-boot-starter-2.1.3.jarmybatis-spring-boot-starter-2.1.3.jar

    mybatis-spring-boot-starter-2.1.4.jar

    mybatis-spring-boot-starter-2.1.4.jarmybatis-spring-boot-starter-2.1.4.jar

    spring-boot-parent.rar

    例如,`spring-boot-starter-web` 添加了HTTP和REST支持,`spring-boot-starter-data-jpa` 提供了与JPA和数据库交互的能力。 4. **构建工具**:虽然没有明确指出使用Maven还是Gradle,但通常 `.rar` 文件关联于...

    spring-boot-security-saml, Spring Security saml与 Spring Boot的集成.zip

    spring-boot-security-saml, Spring Security saml与 Spring Boot的集成 spring-boot-security-saml这个项目在处理 spring-security-saml 和 Spring Boot 之间的平滑集成的同时,在处理内部的配置的gritty和锅炉板的...

    spring-boot spring-security-oauth2 完整demo

    本篇文章将围绕“spring-boot spring-security-oauth2 完整demo”这一主题,详细阐述这三个框架如何协同工作,以及如何通过类似微信的方式获取token并访问资源。 首先,Spring Boot是基于Spring框架的快速开发工具...

    spring-boot-cli下载

    我们来详细了解一下`spring-boot-cli-2.0.0.M1-bin.zip`这个压缩包以及其中的`spring-2.0.0.M1`文件。 首先,`2.0.0.M1`代表的是Spring Boot的里程碑版本(Milestones),这是在正式版本发布前的一个预览版,用于...

    easypoi-spring-boot-starter-4.0.0.jar

    easypoi-spring-boot-starter-4.0.0.jar 包

    spring-boot-samples-master

    3. **数据访问**:"spring-boot-sample-data-jpa"和"spring-boot-sample-data-mongodb"分别演示了如何与关系型数据库(如MySQL、PostgreSQL)和非关系型数据库(如MongoDB)集成,使用JPA和Spring Data进行数据操作...

    spring-boot-starter-kafka示例程序

    spring-boot-starter-kafka示例程序\n 支持springcloud1.5.4,kafka0.8.2.x\n 项目地址:https://github.com/zhyea/spring-boot-starter-kafka

    mybatis-spring-boot-starter-2.0.0.jar

    mybatis mybatis-spring-boot-starter-2.0.0.jar下载

    Spring Boot 入门 - 基础篇(11)- 数据源配置

    在本篇“Spring Boot入门 - 基础篇(11)- 数据源配置”中,我们将探讨如何在Spring Boot项目中配置数据源,以便连接到数据库并执行相关的CRUD操作。Spring Boot以其自动化配置和简化开发流程而受到广泛欢迎,它使得...

    spring-boot-config-yaml.jar

    spring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot-config-yaml.jarspring-boot...

    mybatis-spring-boot-autoconfigure-2.1.3.jar_idea安装maven插件

    mybatis-spring-boot-autoconfigure-2.1.3mybatis-spring-boot-autoconfigure-2.1.3

    graphql-spring-boot-starter, GraphQL的Spring Boot starter.zip

    graphql-spring-boot-starter, GraphQL的Spring Boot starter GraphQL Spring Boot 启动器这是一个用于 GraphQL Java插件项目的Spring Boot 起始。目录概述正在开始运行。版本管理行为准则。捐赠计划确认许可协议...

    spring-boot-web-restfulcrud代码示例

    在“spring-boot-web-restfulcrud”这个项目中,我们关注的是如何使用 Spring Boot 构建一个基于 Web 的 RESTful CRUD(创建、读取、更新和删除)应用。RESTful 风格是一种软件架构风格,用于设计网络应用程序,通过...

    spring-boot-maven-plugin-2.3.0.RELEASE.jar

    java运行依赖jar包

    spring-boot-examples-master.zip

    spring-boot-examples-master示例程序,与各种框架集成,包括: dockercompose-springboot-mysql-nginx spring-boot-actuator spring-boot-banner spring-boot-docker spring-boot-elasticsearch spring-boot-...

Global site tag (gtag.js) - Google Analytics