spring之RestTemplate

从Spring3.0开始,Spring为创建Rest API提供了良好的支持.

REST提供了一个更简单的可选方案。另外,很多的现代化应用都会有移动或富JavaScript客户端,它们都会使用运行在服务器上REST API。

借助 RestTemplate,Spring应用能够方便地使用REST资源 
Spring的 RestTemplate访问使用了模版方法的设计模式.模版方法将过程中与特定实现相关的部分委托给接口,而这个接口的不同实现定义了接口的不同行为.

get请求

第一、getForEntity方法

 

import org.springframework.web.client.RestTemplate;

import org.springframework.beans.factory.annotation.Value;

@Value("${tw-api-url.wbs}") // 同望wbs数据接口地址
private String twApiUrlWbs;

@Value("${tw-api-url.org-tree}")
private String twOrgTree;

@Value("${tw-api-url.user-pro}")
private String twUserPro;

@Autowired
private RestTemplate rt;



@SuppressWarnings("rawtypes") public List<Map> getTwOrgTree(String orgId) { ResponseEntity<JSONObject> forEntity = rt.getForEntity(twOrgTree + "?orgId={1}", JSONObject.class, orgId); List<Map> orgs = new ArrayList<>(0); if (forEntity.getStatusCodeValue() == 200) { JSONObject bodyData = forEntity.getBody(); if (bodyData.getBooleanValue("success")) { // 响应数据格式转换 String orgStr = bodyData.getJSONObject("data").getString("orgEntity"); orgs = JSONObject.parseArray(orgStr, Map.class); } } else { if (log.isInfoEnabled()) log.info("同望wbs数据获取失败,响应状态非 200!"); } return orgs; }
    public transient ResponseEntity getForEntity(String url, Class responseType, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
        ResponseExtractor responseExtractor = responseEntityExtractor(responseType);
        return (ResponseEntity)nonNull(execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables));
    }

******* public class ResponseEntity extends HttpEntity

源码最后调用的方法:

 protected Object doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor responseExtractor)
        throws RestClientException
    {
        ClientHttpResponse response;
        Assert.notNull(url, "URI is required");
        Assert.notNull(method, "HttpMethod is required");
        response = null;
        Object obj;
        try
        {
            ClientHttpRequest request = createRequest(url, method);
            if(requestCallback != null)
                requestCallback.doWithRequest(request);
            response = request.execute();
            handleResponse(url, method, response);
            obj = responseExtractor == null ? null : responseExtractor.extractData(response);
        }
        catch(IOException ex)
        {
            String resource = url.toString();
            String query = url.getRawQuery();
            resource = query == null ? resource : resource.substring(0, resource.indexOf('?'));
            throw new ResourceAccessException((new StringBuilder()).append("I/O error on ").append(method.name()).append(" request for \"").append(resource).append("\": ").append(ex.getMessage()).toString(), ex);
        }
        if(response != null)
            response.close();
        return obj;
        Exception exception;
        exception;
        if(response != null)
            response.close();
        throw exception;
    }

第二种、getForObject

 public transient Object getForObject(String url, Class responseType, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
        HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor(responseType, getMessageConverters(), logger);
        return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
    }

post请求

第一种、postForEntity

 public transient ResponseEntity postForEntity(String url, Object request, Class responseType, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = httpEntityCallback(request, responseType);
        ResponseExtractor responseExtractor = responseEntityExtractor(responseType);
        return (ResponseEntity)nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables));
    }

第二种、postForObject

   public transient Object postForObject(String url, Object request, Class responseType, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = httpEntityCallback(request, responseType);
        HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor(responseType, getMessageConverters(), logger);
        return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
    }

第三种、postForLocation

 public transient URI postForLocation(String url, Object request, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = httpEntityCallback(request);
        HttpHeaders headers = (HttpHeaders)execute(url, HttpMethod.POST, requestCallback, headersExtractor(), uriVariables);
        return headers == null ? null : headers.getLocation();
    }

put请求

@RequestMapping("/put")
public void put() {
    Book book = new Book();
    book.setName("红楼梦");
    restTemplate.put("http://HELLO-SERVICE/getbook3/{1}", book, 99);//{1}是占位符。book是要提交的参数。99是替换占位符的值
}

 public transient void put(String url, Object request, Object uriVariables[])
        throws RestClientException
    {
        RequestCallback requestCallback = httpEntityCallback(request);
        execute(url, HttpMethod.PUT, requestCallback, null, uriVariables);
    }

 delete请求

 public transient void delete(String url, Object uriVariables[])
        throws RestClientException
    {
        execute(url, HttpMethod.DELETE, null, null, uriVariables);
    }

关注公众号,我们就从陌生变成了相识,从此我们就成为了朋友,共同学习共同进步!

 

来都来了,抬起贵手点个赞再走呗!

posted @ 2018-12-10 19:03  逝年的我们  阅读(420)  评论(0编辑  收藏  举报