I. Overview
Codes to achieve an effect, and may be returned to the normal acquisition data:
ResponseEntity<JsonObject> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JsonObject.class,uriVariables);
restTemplate get and POST request type parameter are set, it can be returned directly converted into a customized format such as:
restTemplate.getForObject("http://www.baiud.com",JsonObject.class);
But the exchange can not specify a return type, use only the format converter to convert several of spring provided by default, define other formats will complain or return entity body is empty
post method restTemplate support setting header, but the method does not get support, if now there is a demand, using get methods need to set permissions header, and returns the format I want, then custom HttpMessageConverter comes in handy
Withdraw the spring also very powerful scalability
Two step
New Custom conversion classes:
/ ** * returns the interface request type data format conversion processing, only the processing String-> JSONObject * / public class StringToJsonObjectMessageConverter the extends AbstractHttpMessageConverter <JSONObject> { public StringToJsonObjectMessageConverter () { Super (StandardCharsets.UTF_8, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML); // set the payment type } / ** * HttpMessageConvert whether to accept the processing of this class * / @Override protected Boolean the Supports (<?> class aClass) { // IsAssignableFrom: this class object determines the class or interface with the specified class whether the class or interface parameters indicated by the same, or is a superclass or super interfaces return. JSONObject class == aClass; } // process the data and return @Override protected JSONObject readInternal (Class <? The extends aClass, HttpInputMessage httpInputMessage JSONObject>) throws IOException, HttpMessageNotReadableException { // data converting String temp = StreamUtils.copyToString (httpInputMessage .getBody (), Charset.forName ( "UTF-. 8" )); return .. Tools.getGsonInstance () fromJson (TEMP, JSONObject class ); } // address how to output data Response @Override protected voidwriteInternal (JSONObject jsonObject, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { // continue processing format data converted httpOutputMessage.getBody () Write (jsonObject.getAsByte ());. } }
Configuration changes custom class order:
@Bean public RestTemplate RestTemplate () { HttpComponentsClientHttpRequestFactory httpRequestFactory = new new HttpComponentsClientHttpRequestFactory (); httpRequestFactory.setConnectionRequestTimeout ( 30 * 1000 ); httpRequestFactory.setConnectTimeout ( 30 * 3000 ); httpRequestFactory.setReadTimeout ( 30 * 3000 ); RestTemplate RestTemplate = new new RestTemplate (httpRequestFactory ); // support return JsonObject type of data, you need before String, String pay because all types directly resolve restTemplate.getMessageConverters () the SET (1,. new newStringToJsonObjectMessageConverter ()); // Spring default encoding is converted ISO_8859_1, if the coding distortion can be modified to support Chinese restTemplate.getMessageConverters () the Add (. New new StringHttpMessageConverter (StandardCharsets.UTF_8)); return RestTemplate; }
Breakpoints view:
Three Principles
exchage method into the source point, look to know
//获取HttpMessageConverter集合 Iterator var8 = RestTemplate.this.getMessageConverters().iterator(); //按照索引顺序进行迭代循环解析 while(var8.hasNext()) { HttpMessageConverter<?> messageConverter = (HttpMessageConverter)var8.next(); if (messageConverter instanceof GenericHttpMessageConverter) { GenericHttpMessageConverter<Object> genericConverter = (GenericHttpMessageConverter)messageConverter; if (genericConverter.canWrite((Type)requestBodyType, requestBodyClass, requestContentType)) { if (!requestHeadersx.isEmpty()) { requestHeadersx.forEach((key, values) -> { httpHeadersx.put(key, new LinkedList(values)); }); } if (RestTemplate.this.logger.isDebugEnabled()) { if (requestContentType != null) { RestTemplate.this.logger.debug("Writing [" + requestBody + "] as \"" + requestContentType + "\" using [" + messageConverter + "]"); } else { RestTemplate.this.logger.debug("Writing [" + requestBody + "] using [" + messageConverter + "]"); } } //解析成功直接返回,不会走后面解析器 genericConverter.write(requestBody, (Type)requestBodyType, requestContentType, httpRequest); return; } } else if (messageConverter.canWrite(requestBodyClass, requestContentType)) { if (!requestHeadersx.isEmpty()) { requestHeadersx.forEach((key, values) -> { httpHeadersx.put(key, new LinkedList(values)); }); } if (RestTemplate.this.logger.isDebugEnabled()) { if (requestContentType != null) { RestTemplate.this.logger.debug("Writing [" + requestBody + "] as \"" + requestContentType + "\" using [" + messageConverter + "]"); } else { RestTemplate.this.logger.debug("Writing [" + requestBody + "] using [" + messageConverter + "]"); } } messageConverter.write(requestBody, requestContentType, httpRequest); return; } } //如果都没有解析成功.抛异常 String message = "Could not write request: no suitable HttpMessageConverter found for request type [" + requestBodyClass.getName() + "]"; if (requestContentType != null) { message = message + " and content type [" + requestContentType + "]"; } throw new RestClientException(message);