package com.sw.mes.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sw.mes.yb.agv.dto.AgvReturnResult;

public class EAPHttpUtil {

	
	public static String post(String url, String params,int timeout) {
		return post(url, params,timeout,"application/json");
	}
	
    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, String params,int timeout,String contentType) {
    	String result = "";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
	        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
	        		.setSocketTimeout(timeout).setConnectTimeout(timeout).build();
	        // 创建httppost
	        HttpPost httppost = new HttpPost(url);
	        
	        httppost.setHeader("Authorization", "token_admin");
	        
	        httppost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
//            stringEntity.setContentEncoding("UTF-8");
//            stringEntity.setContentType("application/json");
//            stringEntity.setContentType("application/x-www-form-urlencoded");
            
            if(contentType!=null)
            	stringEntity.setContentType(contentType);
            
            httppost.setEntity(stringEntity);

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                org.apache.http.HttpEntity entity = response.getEntity();
                if (entity != null) {
                	result = EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
        	result = "http请求缺少user-agent字段:"+e.getMessage();
        } catch (UnsupportedEncodingException e1) {
        	result = "转码异常:"+e1.getMessage();
        } catch (IOException e) {
        	result = "IO错误输入输出错误,无效URL连接:"+e.getMessage();
        } catch (Exception e) {
        	result = e.getMessage();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     */
    public static String get(String url, String param) {

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        // 创建httppost
        HttpGet httpGet = new HttpGet(url + "?" + param);

        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                org.apache.http.HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static JSONObject getRequestJson(HttpServletRequest request) {
        JSONObject jsonObject = null;
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            jsonObject = JSONObject.parseObject(responseStrBuilder.toString());

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

        }
        return jsonObject;
    }

    public static String getRequestString(HttpServletRequest request) {

        StringBuilder responseStrBuilder = new StringBuilder();
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseStrBuilder.toString();
    }

}