package com.zjrs.ggfw.portal.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;


public class HttpUtil {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }


    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(15000);
        return factory;
    }


    /**
     * 使用RestTemplate进行请求发送
     *
     * @param url
     * @param param
     * @param httpMethod
     * @return
     */
    public static String restTemplate(String url, String param, HttpMethod httpMethod) {

        try {
            RestTemplate restTemplate = new HttpUtil().restTemplate(new HttpUtil().simpleClientHttpRequestFactory());
            //请求头设置
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "application/json");
            //封装请求头和body
            HttpEntity<String> requestEntity = new HttpEntity<String>(!StringUtils.isEmpty(param) ? param : null, requestHeaders);
            //发送请求
            ResponseEntity<String> exchange = restTemplate.exchange(url, httpMethod, requestEntity, String.class);
            return exchange.getBody();
        } catch (Exception e) {
            throw e;
        }
    }
}
