Insight spring RestTemplate

炸雞店老闆發表於2018-01-03

insight spring 提供的rest操作,以及jdk自帶URL http訪問的實現。

spring RestTemplate 執行流程

/**
 * http請求,根據指定的方法訪問URI
 * @param requestCallback write請求物件至 request。藉助HttpMessageConverter 元件,轉換物件,如json的序列化
 *      類比前端ajax請求,JSON.stringify(request)
 * @param responseExtractor 從response 解析返回值。responseExtractor 封裝HttpMessageConverter 元件,用以轉換response,比如json的反序列化。
 *      new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
 */
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) {
    try {
        // 1.構造request (open a connection, set timeout...)
        ClientHttpRequest request = createRequest(url, method);
        if (requestCallback != null) {
            // 2.序列化request,write bytes to request body
            requestCallback.doWithRequest(request);
        }
        // 3.check、connect,構造response
        response = request.execute();
        // 4.handle error
        handleResponse(url, method, response);
        if (responseExtractor != null) {
            // 5.解析、反序列化response
            return responseExtractor.extractData(response);
        }
    } catch (IOException ex) {
        // ......
    } finally {
        // 6.切記close InputStream
        if (response != null) {
            response.close();
        }
    }
}

JDK 自帶URL實現的http訪問
對應上述的執行流程,JDK URL的具體操作

/*
 * createRequest 實現
 */
// 根據url協議建立對應的URLConnection,不會真正的建立網路連線.
URLConnection connection = (HttpURLConnection) url.openConnection();
// A timeout of zero is interpreted as an infinite timeout.
connection.setConnectTimeout(this.connectTimeout);
connection.setReadTimeout(this.readTimeout);
connection.setDoInput(true);
// 如果是POST、PUT、PATCH、DELETE方法,需要enable output
connection.setDoOutput(true);
// 預設方法是GET.
connection.setRequestMethod(httpMethod);
/**
 * request.execute 實現
 */
connection.setRequestProperty("Cookie", headerValue);
connection.addRequestProperty(headerName, actualHeaderValue);
// 構造Response,responseBody = connection.getInputStream()
new SimpleClientHttpResponse(connection)

相關文章