http工具类最佳实践探究

142 阅读1分钟

java项目中http的远程调用如何做最规范,初始化好,是交给spring容器,还是直接静态初始化。 静态初始化方式如下

public class HttpClientUtil {
    private static final Log LOGGER = LogFactory.getLog(HttpClientUtil.class);
    
    private HttpClientUtil() {
        
    }

    private static final RestTemplate restTemplate;

    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(500);
        factory.setReadTimeout(1000);
        restTemplate = new RestTemplate(factory);
    }

    /**
     * 发送http请求封装
     *
     * @param url   请求地址
     * @param param 参数
     * @param type  返回值类型
     * @param <T>   返回值用到的泛型
     * @return 返回值
     */
    public static <T> T msRequestForHttp(String url, Object param, TypeReference<T> type) {
        T responseObject = null;
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            org.springframework.http.HttpEntity<Object> httpEntity = new org.springframework.http.HttpEntity<Object>(param, httpHeaders);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            String responseJson = response.getBody();
            responseObject = JSON.parseObject(responseJson, type);
        } catch (Exception e) {
            LOGGER.error("HTTP调用,URL:" + url + ",请求异常:", e);
        }
        return responseObject;
    }
 }