Spring的RestTemplata使用的具体方法
基本概念
SpringRestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,所以很多客户端比如Android或者第三方服务商都是使用RestTemplate请求restful服务。
spring-web的RestTemplata是对java底层http的封装,使用RestTemplata用户可以不再关注底层的连接建立,并且RestTemplata不仅支持Rest规范,还可以定义返回值对象类型。
在使用中可以直接new一个RestTemplate对象,在我们创建的RestTemplate对象中会有一些返回消息的消息转换器,可以根据返回数据的MediaType寻找对应的转换器并进行MediaType转换。自己也可以创建消息转换器,创建一个类继承AbstractGenericHttpMessageConverter
RestTemplate对象在底层通过使用java.net包下的实现创建HTTP请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式:
- 一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。
- 一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。
RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1,我们可以自己定义超时时间
SimpleClientHttpRequestFactoryfactory=newSimpleClientHttpRequestFactory(); //设置连接超时,单位毫秒 factory.setConnectTimeout(5000); //设置读取超时,单位毫秒 factory.setReadTimeout(10000); RestTemplaterestTemplate=newRestTemplate(factory);
使用GET请求:
Stringurl="http://localhost:80/mandy/login.json?account=123456&password=123456"; Resultres=restTemplate.getForObject(url,Result.class);
RestTemplate源码:
@Override publicTgetForObject(Stringurl,Class responseType,Object...urlVariables)throwsRestClientException{ RequestCallbackrequestCallback=acceptHeaderRequestCallback(responseType); HttpMessageConverterExtractor responseExtractor= newHttpMessageConverterExtractor (responseType,getMessageConverters(),logger); returnexecute(url,HttpMethod.GET,requestCallback,responseExtractor,urlVariables); }
使用get请求直接将参数拼接到地址上最好,不知道什么原因如果使用第三个参数,即便是MultiValueMap类型也不行(网上有人说用MultiValueMap类型可以,我试了不行)
使用POST请求:
HashMapmap=newHashMap (); map.put("name","测试"); map.put("account","qwer"); map.put("password","qwer"); ObjectMappermapper=newObjectMapper(); StringjsonStr=null; try{ jsonStr=mapper.writeValueAsString(map); }catch(Exceptione){ e.printStackTrace(); } //创建HTTP头部实体,填充头部信息,比如数据格式 HttpHeadershttpHeaders=newHttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); //创建HTTP实体,可以直接利用构造方法将请求体和请求头放进去 HttpEntity httpEntity=newHttpEntity (jsonStr2,httpHeaders); Stringurl="http://localhost:80/mandy/user_enable.json"; //调用方法进行请求 Resultres2=restTemplate.postForObject(url,httpEntity,Result.class);
RestTemplate源码:
@Override publicTpostForObject(Stringurl,Objectrequest,Class responseType,Object...uriVariables) throwsRestClientException{ RequestCallbackrequestCallback=httpEntityCallback(request,responseType); HttpMessageConverterExtractor responseExtractor= newHttpMessageConverterExtractor (responseType,getMessageConverters(),logger); returnexecute(url,HttpMethod.POST,requestCallback,responseExtractor,uriVariables); }
使用PUT请求:
HashMapmap=newHashMap (); map.put("user_id","1"); map.put("enable",0); ObjectMappermapper=newObjectMapper(); StringjsonStr=null; try{ jsonStr=mapper.writeValueAsString(map); }catch(JsonProcessingExceptione){ e.printStackTrace(); } //创建HTTP头部实体,填充头部信息,比如数据格式 HttpHeadershttpHeaders=newHttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); //创建HTTP实体,可以直接利用构造方法将请求体和请求头放进去 HttpEntity httpEntity=newHttpEntity (jsonStr,httpHeaders); Stringurl="http://localhost:80/mandy/user_enable.json"; restTemplate.put(url,httpEntity);
RestTemplate源码:
@Override publicvoidput(Stringurl,Objectrequest,Object...urlVariables)throwsRestClientException{ RequestCallbackrequestCallback=httpEntityCallback(request); execute(url,HttpMethod.PUT,requestCallback,null,urlVariables); }
这个方法有个小的缺点就是没有请求结果的返回值,如果需要用到返回值,就不能用这个方法。
如果要使用delete类型的请求,RestTemplate的put方法的参数列中只有下面几种
@Override publicvoiddelete(Stringurl,Object...urlVariables)throwsRestClientException{ execute(url,HttpMethod.DELETE,null,null,urlVariables); } @Override publicvoiddelete(Stringurl,MapurlVariables)throwsRestClientException{ execute(url,HttpMethod.DELETE,null,null,urlVariables); } @Override publicvoiddelete(URIurl)throwsRestClientException{ execute(url,HttpMethod.DELETE,null,null); }
这些方法并没有给我们参数让我们放请求体内容,所以如果要直接使用RestTemplate提供的Delete方法,接口必须使用restful风格,将参数放在地址中,通过@PathVariable(value="")注解将参数获取到。
重点:其实我们可以直接使用RestTemplate的exchange方法,如下
@Override publicResponseEntity exchange(Stringurl,HttpMethodmethod, HttpEntity>requestEntity,Class responseType,Object...uriVariables)throwsRestClientException{ RequestCallbackrequestCallback=httpEntityCallback(requestEntity,responseType); ResponseExtractor >responseExtractor=responseEntityExtractor(responseType); returnexecute(url,method,requestCallback,responseExtractor,uriVariables); }
这里只列举了一个方法,其他的可以看源码,这个方法可以进行所有类型的请求。
在这个方法中,method参数可以通过HTTPMethod枚举来进行获取,requestEntity参数是自己封装的HttpEntity实体,包含请求体和请求头,responseType参数是返回结果的映射类,uriVariables这个参数给我的印象就是鸡肋(个人看法),获取请求返回接口可以通过方法返回值的getBody()方法获取。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。