Springboot - a more elegant way to send a request HTTP request

Reference: https://www.cnblogs.com/javazhiyin/p/9851775.html

rest Template

Spring is to provide clients RestTemplate used to access services Rest easy access to a variety of methods HttP services, the efficiency can greatly be prompted to write client

Http development before we are with the apache HttpClient development, code complexity. The following is a get request packaged

 public static JSONObject doGet(String url) {
        JSONObject jsonResult = null;
        try (CloseableHttpClient client = HttpClients.createDefault();) {
            HttpGet request = new HttpGet(url);
            request.setConfig(requestConfig);
            try (CloseableHttpResponse response = client.execute(request);) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    String responseContent = EntityUtils.toString(entity);
                    jsonResult = JSONObject.parseObject(responseContent);
                } else {
                    log.error ( "the Get request failed: {}, status codes: {}" , URL, statusCode);
                }
            }
        } catch (IOException e) {
            log.error ( "Exception the Get Request: {}, {}" , URL, e.getMessage ());
            e.printStackTrace ();
        }
        return jsonResult;
    }

This tutorial will achieve RestTemplate in the spring ecological get and post request and analyzing the request to specify the type of request and exchange RestTemplate core source code.

First, Jane book RestTemplate

Spring is a client-side synchronous core classes, simplifies communication and http service and to meet RestFul principle, program code may provide a URL to it, and the extraction result. By default, RestTemplate jdk dependent default HTTP connection tool. 
Of course you can also switch to a different property by setRequestFactory HTTP sources, such as Apache HttpComponents, Netty and OkHttp.

RestTemplate can greatly simplify the difficulty of submitting form data, and with features automatically convert JSON data, but only to understand the composition of the structure HttpEntity of (header, body), and understand the difference between urlVariables in order to regular control over their usage.

The main entrance of the class is to develop according to six methods of HTTP

 

 

 In addition, exchange and can excute general method described above.

Use Example HttpMessageConverter converted into an HTTP message POJO POJO into or from a message within the HTTP RestTemplate default. By default, registered to the mime type of converter, but also other converters can register by setMessageConverters.

In fact, this point in time using imperceptible, there are many ways a responseType parameters, it allows you to incoming object is mapped into a response body, and then the bottom with HttpMessageConverter to do mapping
HttpMessageConverterExtractor<T> responseExtractor =
                new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);

HttpMessageConverter.java

public  interface HttpMessageConverter types <T> {
         // indicating whether this converter can read the given class. 
    boolean canRead (Class <?> clazz, @Nullable MediaType mediaType);
 
        // indicates whether this converter can be addressed given class. 
    boolean canWrite (Class <?> clazz, @Nullable MediaType mediaType);
 
        //返回List<MediaType>
    List<MediaType> getSupportedMediaTypes();
 
        //读取一个inputMessage
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;
 
        //往output message写一个Object
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;
 
}

In the interior, RestTemplate default SimpleClientHttpRequestFactory and DefaultResponseErrorHeader to handle the creation and Http errors, but can also be covered by setRequestFactory and setErrorHander

Two, get practice request

public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){}
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)
public <T> T getForObject(URI url, Class<T> responseType)

getForObject () is actually more than getFacEntity () it contains more than Http will turn into a POJO functions, but does not address response capabilities. Should get close to it is the POJO

POJO

public class Notice {
    private int status;
    private Object msg;
    private List<DataBean> data;
}
public  class DataBean {
  private int noticeId;
  private String noticeTitle;
  private Object noticeImg;
  private long noticeCreateTime;
  private long noticeUpdateTime;
  private String noticeContent;
}

Guess you like

Origin www.cnblogs.com/baizhuang/p/11870982.html