RestTemplate实现访问远程Http服务

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实践

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,428评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,959评论 6 342
  • 大好时光过成了将死之生活 感觉现在最可悲的就是没有方向、没有目标、也没有喜欢
    小太阳蒙蒙哒阅读 160评论 0 1
  • 开贴记录我的写作历程,每天更新! 1月目标:码字10万,粉丝增加100个,不找借口,锻炼执行力。 第1天:码字17...
    孽因阅读 203评论 51 0