package com.winsun.smsUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    public static int httpPostMethodNoReTry( String url, Map<String, String> pairs ) throws Exception {
        String ret = "";
        int statusCode = 0;
        CloseableHttpClient httpclient = null;
        HttpPost request = null;
        try {
            httpclient = HttpClients.createDefault();
            request = new HttpPost( url );
            /** 请求参数 */
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for( Map.Entry<String, String> e : pairs.entrySet() ) {
                nvps.add( new BasicNameValuePair( e.getKey(), e.getValue() ) );
            }
            request.setEntity( new UrlEncodedFormEntity( nvps, "UTF-8" ) );
            /** 超时时间 5s 重试次数 3 */
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout( 5000 )
                    .setConnectTimeout( 5000 ).build();// 设置请求和传输超时时�?
            request.setConfig( requestConfig );
            // 发�?�请�?
            CloseableHttpResponse response = httpclient.execute( request );
            HttpEntity entity = response.getEntity();
            ret = EntityUtils.toString( entity );
            statusCode = response.getStatusLine().getStatusCode();
            if( (statusCode + "").charAt( 0 ) != '2' ) { // 返回�?2XX以外属于请求不成功范�?
                throw new Exception( "请求失败" );
            }
        }
        catch( Exception e ) {
            throw new Exception( e );
        }
        finally {
            if( null != request ) {
                request.releaseConnection();
            }
        }
        return statusCode;
    }


    public static String httpPostMethodNoReTryWithStr(String url, Map<String, String> pairs )
            throws Exception {
        String ret = "";
        int statusCode = 0;
        CloseableHttpClient httpclient = null;
        HttpPost request = null;
        try {
            httpclient = HttpClients.createDefault();
            request = new HttpPost(url);

            /** 请求参数 */
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> e : pairs.entrySet()) {
                nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            /** 超时时间 5s 重试次数 3 */
            HttpHost proxy = new HttpHost("172.18.101.170", 3128);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000)
                    .setProxy(proxy).build();
            request.setConfig(requestConfig);
            // 发�?�请�?
            log.info(request.getMethod());
            CloseableHttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            ret = EntityUtils.toString(entity);
            statusCode = response.getStatusLine().getStatusCode();
            if ((statusCode + "").charAt(0) != '2') { // 返回�?2XX以外属于请求不成功范�?
                throw new Exception("request error");
            } else {
                return ret;
            }
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            if (null != request) {
                request.releaseConnection();
            }
        }
    }

    /**
     * 功能描述�? 以post的方式发送请�?
     *
     * @param url
     * @param pairs
     *            参数键�?�对
     * @return
     *
     */
    public static String httpPostMethod(String url, Map<String, String> pairs) {
        String ret = "";
        int statusCode = 0;
        CloseableHttpClient httpclient = null;
        HttpPost request = null;
        try {
            httpclient = HttpClients.createDefault();
            request = new HttpPost(url);
            /** 请求参数 */
            if(null != pairs){
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> e : pairs.entrySet()) {
                    nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
                }
                request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            }
            /** 超时时间 5s 重试次数 3 */
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();// 设置请求和传输超时时�?
            request.setConfig(requestConfig);
            // 发�?�请�?
            CloseableHttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            ret = EntityUtils.toString(entity);
            statusCode = response.getStatusLine().getStatusCode();
            /** 处理对方服务器redirect的情�? 返回302/303 再次发�?�请求到重定向地�? */
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String locationUrl = response.getLastHeader("Location").getValue();
                if (StringUtils.isNotBlank(locationUrl)) {
                    ret = httpPostMethod(locationUrl, pairs); // 用跳转后的页面重新请求�??
                }
            } else if ((statusCode + "").charAt(0) != '2') { // 返回�?2XX以外属于请求不成功范�?
                return "";
            }
        } catch (Exception e) {
            try {
                e.printStackTrace();
                Thread.sleep(20L);
                CloseableHttpResponse response = httpclient.execute(request);
                HttpEntity entity = response.getEntity();
                ret = EntityUtils.toString(entity);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } finally {
            if (null != request) {
                request.releaseConnection();
            }
        }
        return ret;
    }

    public static String httpPostMethod(String url) throws Exception {
        String ret = "";
        int statusCode = 0;
        CloseableHttpClient httpclient = null;
        HttpGet request = null;
        try {
            httpclient = HttpClients.createDefault();
            request = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000)
                    .setConnectTimeout(5000).build();// 设置请求和传输超时时�?
            request.setConfig(requestConfig);
            // 发�?�请�?
            CloseableHttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            ret = EntityUtils.toString(entity);
            statusCode = response.getStatusLine().getStatusCode();
            /** 处理对方服务器redirect的情�? 返回302/303 再次发�?�请求到重定向地�? */
            if ((statusCode + "").charAt(0) != '2') { // 返回�?2XX以外属于请求不成功范�?
                throw new Exception("查询失败");
            }
            return ret;
        } finally {
            if (null != request) {
                request.releaseConnection();
            }
        }
    }
}
