package com.njcn.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
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 org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hongawen
 * @Date: 2018/7/18 14:08
 */
public class HttpClientUtils {

    /**
     * httpClient执行post请求访问目标，返回状态码以及响应体的数据
     * @param url post请求的目标地址
     * @param params 携带的参数
     */
    public static CloseableHttpResponse excutePost(String url, Map<String,String> params) throws Exception {
        CloseableHttpClient closeableHttpClient= HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        List<NameValuePair> nvps=new ArrayList<>();
        if(!CollectionUtils.isEmpty(params)){
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse closeableHttpResponse=closeableHttpClient.execute(httpPost);
        return closeableHttpResponse;
    }

    /**
     *httpClient执行get请求访问目标，返回状态码以及响应体的数据
     * @param url get请求url地址
     */
    public static CloseableHttpResponse excuteGet(String url) throws Exception{
        CloseableHttpClient closeableHttpClient= HttpClients.createDefault();
        HttpGet httpGet=new HttpGet(url);
        CloseableHttpResponse closeableHttpResponse=closeableHttpClient.execute(httpGet);
        return closeableHttpResponse;
    }


    /**
     *  httpClient执行post请求访问目标，参数为json格式，返回状态码以及响应体的数据
     * @param url post请求url地址
     * @param jsonObject json参数
     */
    public static String excutePostJson(String url, JSONObject jsonObject)throws Exception{
        CloseableHttpClient closeableHttpClient= HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse closeableHttpResponse=closeableHttpClient.execute(httpPost);
        HttpEntity e = closeableHttpResponse.getEntity();
        return EntityUtils.toString(e);
    }


    /**
     * 调用wsdl类型webService方服务
     */
    public static String excuteWsdl(String url,String soapRequestData){
        //soap服务地址
        //创建httpcleint对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建http Post请求
        HttpPost httpPost = new HttpPost(url);
        // 构建请求配置信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
                .setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
                .setSocketTimeout(3 * 1000) // 数据传输的最长时间10s
                .build();
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            //采用SOAP1.1调用服务端，这种方式能调用服务端为soap1.1和soap1.2的服务
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", "");
            //采用SOAP1.2调用服务端，这种方式只能调用服务端为soap1.2的服务
            // httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(soapRequestData, Charset.forName("UTF-8"));
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
                return content;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                return null;
            }
        }
    }
}
