RestTemplate实现访问远程Http服务

2017-06-20  本文已影响0人  胖胖的半山兄

RestTemplate是spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用Java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。ClientHttpRequestFactory接口主要提供了两种实现方式:
一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。
一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。[本段抄]

本文使用SimpleClientHttpRequestFactory实现ClientHttpRequestFactory接口

public class SimpleRestClient {

    private static RestTemplate restTemplate;

    private SimpleRestClient() {

    }

    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(15000);
        factory.setConnectTimeout(15000);
        restTemplate = new RestTemplate(factory);

        CustomHttpMessageConverter converter = new CustomHttpMessageConverter();
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(converter);
        restTemplate.setMessageConverters(converters);

    }

    public static RestTemplate getClient() {
        return restTemplate;
    }

}

get方式

    //Object 对象为Response返回的具体类型,需根据实际返回对象创建实体类等
    //参数直接放在URL中
    Object result = restTemplate.getForObject("http://localhost:8080/xxx/test?appid=1", Object.class);
    
    // 参数使用可变参数 ...
    int appid = 1;
    Object result = restTemplate.getForObject("http://localhost:8080/xxx/test?appid={appid}", Object.class, appid);

    //参数使用MAP传递
    Map<String,Object> urlVariables = new HashMap<String,Object>();
    urlVariables.put("appid", 1);
    Object result = restTemplate.getForObject("http://localhost:8080/xxx/test", Object.class, urlVariables);

post方式

    //postForObject 使用方式与get基本相同
    Object result = restTemplate
            .postForObject("http://localhost:8080/xxx/test", null, UmBenefitRuleResponse.class);

put方式

    //参数同上三种方式
    restTemplate.put("http://localhost:8080/xxx/test" ,null);

delete方式

    //参数同上三种方式
    restTemplate.delete("http://localhost:8080/xxx/test?appid={appid}",appid);

推荐博文:RestTemplate实践

上一篇 下一篇

猜你喜欢

热点阅读