package net.northking.cctp.mobile.util;

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.mobile.exception.MobileRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

public class HttpUtils<T> {

    private static final RestTemplate restTemplate;

    private static final RestTemplate downLoadRestTemplate;

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(60000);
        restTemplate = new RestTemplate(factory);

        SimpleClientHttpRequestFactory downloadFactory = new SimpleClientHttpRequestFactory();
        downloadFactory.setConnectTimeout(15000);
        downloadFactory.setReadTimeout(10*60*1000);
        downLoadRestTemplate = new RestTemplate(downloadFactory);
    }


    public static <T> T doGet(URI uri, HttpHeaders headers ,Class<T> responseType){
        ResponseEntity<T> response = null;
        HttpEntity httpEntity = null;
        try {
            if (null != headers) {
                httpEntity = new HttpEntity(null, headers);
            }
            response = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, responseType);
        } catch (Exception e) {
            logger.error("请求出错,地址：{}，原因：{}",uri.getPath(),e);
            throw new PlatformRuntimeException(new MobileRuntimeException(50000,String.format("http请求【%s】出错", uri.getPath())));
        }
        return response.getBody();
    }


}
