package com.reyun.check.phonemsg;
/***
 * 发短信接口
 */

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class HttpClientUtil
{
    public final static String REQUEST_HEADER = "x-forwarded-for";

    String servicetoken;
    String receiver;
    String type;
    static String phone_url;
    static String title;
    public HttpClientUtil() {
        this.receiver = "q20180308144739930";
        this.servicetoken = "e15057cc527dd4bdc054dce19a1316e9";
        this.type="sms";
        this.phone_url="http://www.linkedsee.com/alarm/cloudchannel";
        this.title="notice_sms";
    }

    public void sendMsg(String description) throws JSONException{
        JSONObject json = new JSONObject();
        json.put("receiver",this.receiver);
        json.put("type", this.type);
        json.put("title",this.title );
        json.put("content", description);
        HttpClientUtil.httpPostWithJson(json ,this.phone_url,this.servicetoken);
    }
    /**
     * 日志处理类
     */

    // 读取超时  
    private final static int SOCKET_TIMEOUT = 60000;
    // 连接超时  
    private final static int CONNECTION_TIMEOUT = 60000;
    // 每个HOST的最大连接数量  
    private final static int MAX_CONN_PRE_HOST = 20;
    // 连接池的最大连接数  
    private final static int MAX_CONN = 100;
    // 连接池  
    private final static HttpConnectionManager httpConnectionManager;
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * Http get请求，获取结果.
     *
     * @param url
     * @param ip
     * @return
     */
    public static String doHttpGetRequest(String url, String ip)
    {
        HttpClient httpClient = new HttpClient(httpConnectionManager);
        resetRequestHeader(httpClient, ip);
        HttpMethod method = new GetMethod(url);
        return executeMethod(httpClient, method);
    }

    public static String doHttpGetRequest4Mobile(String url, String ip)
    {
        HttpClient httpClient = new HttpClient(httpConnectionManager);
        resetRequestHeader4Mobile(httpClient, ip);
        HttpMethod method = new GetMethod(url);
        return executeMethod(httpClient, method);
    }



    private static String executeMethod(HttpClient httpClient, HttpMethod method){
        return executeMethod(httpClient, method, "ISO-8859-1", "GB2312");
    }

    private static String executeMethod(HttpClient httpClient, HttpMethod method, String readCharsetName, String writeCharsetName)
    {
        String response = null;
        try {
            httpClient.executeMethod(method);
        }
        catch (IOException e) {
            try {
                logger.error("执行HTTP请求" + method.getURI().toString() + "时，发生异常！", e);
            }
            catch (URIException e1) {
                logger.error("URIException", e1);
            }
        }
        finally {
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                StringBuffer stringBuffer = new StringBuffer();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), readCharsetName));
                    String str = "";

                    while ((str = reader.readLine()) != null) {
                        stringBuffer.append(new String(str.getBytes(readCharsetName), writeCharsetName));
                    }
                }
                catch (IOException e) {
                    try {
                        logger.error("执行HTTP响应结果" + method.getURI().toString() + "时，发生异常！", e);
                    }
                    catch (URIException e1) {
                        logger.error("URIException", e1);
                    }
                }
                response = stringBuffer.toString();
            }
            method.releaseConnection();
        }
        return response;
    }

    /**
     * 设置一下返回错误的通用提示,可以自定义格式.
     *
     * @param reason
     * @return
     */
    public static String returnError(String reason)
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
        buffer.append("<Response>");
        buffer.append("<Success>false</Success>");
        buffer.append("<reason>");
        buffer.append(reason);
        buffer.append("</reason>");
        buffer.append("</Response>");
        return buffer.toString();
    }

    /**
     * 将客户IP写入请求头
     * 这个设置可以伪装IP请求,注意使用
     *
     * @param client
     * @param ip
     * @return
     */
    public static void resetRequestHeader(HttpClient client, String ip)
    {
        List<Header> headers = new ArrayList<Header>();
        headers.add(new Header(REQUEST_HEADER, ip));
        headers.add(new Header("Servicetoken", "69fc19debf4c8cf50d6778de556186d5"));
        client.getHostConfiguration().getParams().setParameter(
                "http.default-headers", headers);
        client.getHostConfiguration().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    }

    public static void resetRequestHeader4Mobile(HttpClient client, String ip)
    {
        List<Header> headers = new ArrayList<Header>();
        headers.add(new Header(REQUEST_HEADER, ip));
        client.getHostConfiguration().getParams().setParameter(
                "http.default-headers", headers);
        client.getHostConfiguration().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
    }

    /**
     * Post请求短信通知接口
     * @param jsonObj
     * @param url
     * @return
     */
    public static boolean httpPostWithJson(JSONObject jsonObj, String url,String servicetoken){
        boolean isSuccess = false;

        HttpPost post = null;
        try {
            org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();

            post = new HttpPost(url);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            if(StringUtils.isNotBlank("Servicetoken")) post.setHeader("Servicetoken", servicetoken);

            // 构建消息实体
            StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);

            HttpResponse response = httpClient.execute(post);

            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == org.apache.http.HttpStatus.SC_OK){
                isSuccess = true;
                // 获取响应输入流
                String result = "";
                InputStream inStream = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                result = strber.toString();
                logger.info("--------------------------"+result);
            }

        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }finally{
            if(post != null){
                try {
                    post.releaseConnection();
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return isSuccess;
    }

    public static void main(String[] args)
    {
        try{
            String url = "http://www.linkedsee.com/alarm/cloudchannel";
            JSONObject json = new JSONObject();
            json.put("receiver","18610646715");
            json.put("type", "sms");
            json.put("title", "notice_sms");
            json.put("content", "短信测试!!!!");

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    static {
        httpConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = httpConnectionManager.getParams();
        params.setConnectionTimeout(CONNECTION_TIMEOUT);
        params.setSoTimeout(SOCKET_TIMEOUT);
        params.setDefaultMaxConnectionsPerHost(MAX_CONN_PRE_HOST);
        params.setMaxTotalConnections(MAX_CONN);
    }


}
