package com.lion.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpSession;

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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import jodd.util.StringUtil;

/**
 * 类描述   http请求工具类
 * @author mt.W
 * @since 2019年10月24日
 */
public class HttpUtil {
	public static Logger log4j=Logger.getLogger(HttpUtil.class);
	
	/**
	 * 方法描述	短信http请求
	 * @author cpf
	 * @since 2019年4月12日
	 * @param url
	 * @param paramMap
	 * @return	
	 */
	public static String DXdoPost(String url,Map<String ,Object> paramMap){
		CloseableHttpClient httpClient=null;
		CloseableHttpResponse httpResponse=null;
		String result="";
		//创建httpClient实例
		httpClient=HttpClients.createDefault();
		//创建httpPost远程连接实例
		HttpPost httpPost=new HttpPost(url);
		//配置请求参数实例
		RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(35000)//设置连接主机服务超时时间
				.setConnectionRequestTimeout(35000)//设置连接请求超时时间
				.setSocketTimeout(60000)//设置读取数据连接超时时间
				.build();
		//为httpPosy实例设置配置
		httpPost.setConfig(requestConfig);
		//配置请求头	
		//添加请求的编码格式
		httpPost.addHeader("Content-Type", "application/json;charset=GBK");
		//设置请求的编码格式
		//设置请求的报文头部的编码	
		httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=GBK"));// 
		//设置期望服务端返回的编码	  
		//设置服务器返回的编码格式
		httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
		//封装post请求参数
		if(paramMap!=null && paramMap.size()>0){//通过接口提交参数时, 参数内容必须为GB2312或GBK 编码。
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			//通过map集成entrySet 方法获取entity
			Set<Entry<String,Object>> entrySet=paramMap.entrySet();
			//循环遍历，获取迭代器
			Iterator<Entry<String,Object>> iterator=entrySet.iterator();
			while(iterator.hasNext()){
				Entry<String , Object> mapEntry =iterator.next();
				nvps.add(new BasicNameValuePair(mapEntry.getKey(),mapEntry.getValue().toString()));
			}
			//为httpPost设置封装好的请求参数
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps,"GBK"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			try {
				//httpClient对象执行post请求，并返回相应参数对象
				httpResponse=httpClient.execute(httpPost);
				 //获取响应码
		        int statusCode = httpResponse.getStatusLine().getStatusCode();
		        HttpEntity  entity=httpResponse.getEntity();
		        if (statusCode == 200) {
		        	result = EntityUtils.toString(entity);
		        } else {
		        	log4j.error("HTTP请求出现异常:"+result);
		        	result="";
		        }
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//关闭资源
				if(httpResponse!=null){
					try {
						httpResponse.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(httpClient!=null){
					try {
						httpClient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}//if  end
		return "";
	}

	/**
	 * 
	 * 方法描述  http GET请求方法
	 * @author mt.W
	 * @since 2019年10月24日
	 * @param url 请求接口url地址
	 * @return
	 */
	public static String httpGet(String url){
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
             response = httpClient.execute(get);
            if(response != null && response.getStatusLine().getStatusCode() == 200)
          {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
            }
            //new String(result.getBytes("iso8859-1"),"utf-8");
            return result;
        } catch (IOException e) {
            e.printStackTrace();
     }finally {
            try {
                httpClient.close();
                if(response != null)
                 {
                     response.close();
                }
            } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return null;
    }
	
	/**
	 * 方法描述	短信接口
	 * @author cpf
	 * @since 2019年4月2日
	 * @return	
	 */
	public static String RandomNum(String UserNumber,HttpSession session,String dxSpCode ,String dxLoginName,String dxPassword,String dxurl) throws UnsupportedEncodingException{
		int num = (int) ((Math.random()*9+1)*100000);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("SpCode", dxSpCode);
		map.put("LoginName", dxLoginName);
		map.put("Password",dxPassword);
		map.put("MessageContent", "尊敬的用户,您本次的验证码为"+num+",请妥善保管.");
		map.put("UserNumber", UserNumber);
		map.put("ScheduleTime", "");
		map.put("f", "1");
		String result=HttpUtil.DXdoPost(dxurl, map);
		String rnum = "" ;
		String describle="";
		if(StringUtil.isNotEmpty(result)){
			result=new String(result.getBytes("ISO-8859-1"),"GBK");
			String results[] = result.split("&");
			for(int i =0;i<results.length;i++){
				if(results[i].indexOf("result=")>=0){
					rnum = results[i].substring(7,results[i].length());
				}
				if(results[i].indexOf("description=")>=0){
					describle=results[i].substring(12,results[i].length());
				}
			}
			log4j.error(result);
			if(rnum.equals("0")){
				session.setAttribute("yzcode", num);
				session.setAttribute("phone", UserNumber);
				return Util.responseString("true", describle);
			}
			return Util.responseString("false", describle);
		}
		return Util.responseString("fasle", "当前业务繁忙,请稍后再试");
	}
	
	/**
	 * 方法描述	http  POST请求
	 * @author cpf
	 * @since 2019年4月2日
	 * @param url
	 * @param paramMap
	 * @return	
	 */
	public static String doPost(String url,Map<String ,Object> paramMap){
		CloseableHttpClient httpClient=null;
		CloseableHttpResponse httpResponse=null;
		String result="";
		//创建httpClient实例
		httpClient=HttpClients.createDefault();
		//创建httpPost远程连接实例
		HttpPost httpPost=new HttpPost(url);
		//配置请求参数实例
		RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(35000)//设置连接主机服务超时时间
				.setConnectionRequestTimeout(35000)//设置连接请求超时时间
				.setSocketTimeout(60000)//设置读取数据连接超时时间
				.build();
		//为httpPosy实例设置配置
		httpPost.setConfig(requestConfig);
		//配置请求头
		httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		//设置请求的报文头部的编码
		httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
		//设置期望服务端返回的编码
		httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
		//封装post请求参数
		if(paramMap!=null && paramMap.size()>0){
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			//通过map集成entrySet 方法获取entity
			Set<Entry<String,Object>> entrySet=paramMap.entrySet();
			//循环遍历，获取迭代器
			Iterator<Entry<String,Object>> iterator=entrySet.iterator();
			while(iterator.hasNext()){
				Entry<String , Object> mapEntry =iterator.next();
				nvps.add(new BasicNameValuePair(mapEntry.getKey(),mapEntry.getValue().toString()));
			}
			//为httpPost设置封装好的请求参数
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			try {
				//httpClient对象执行post请求，并返回相应参数对象
				httpResponse=httpClient.execute(httpPost);
				 //获取响应码
		        int statusCode = httpResponse.getStatusLine().getStatusCode();
		        HttpEntity  entity=httpResponse.getEntity();
		        if (statusCode == 200) {
		        	result = EntityUtils.toString(entity);
		        } else {
		        	log4j.error("HTTP请求出现异常:"+result);
		        	result="";
		        }
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//关闭资源
				if(httpResponse!=null){
					try {
						httpResponse.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(httpClient!=null){
					try {
						httpClient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}//if  end
		return "";
	}
	public static String sendHttpUrl(String url,String data){
		String encoding = "UTF-8";   
	    HttpURLConnection httpConnection = null;
	    PrintWriter printWriter = null;//
        StringBuilder stringBuilder = new StringBuilder(); // 用来存储响应数据
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String resultJson = "";
		try {
 
            URL targetUrl = new URL(url);
            // 新建链接实例
            httpConnection = (HttpURLConnection) targetUrl.openConnection();
            // 设置链接超时时间，单位毫秒
            httpConnection.setConnectTimeout(2000);
            // 设置读取数据超时时间，单位毫秒
            httpConnection.setReadTimeout(2000);
            
            httpConnection.setRequestProperty("accept", "*/*");
            httpConnection.setRequestProperty("connection", "Keep-Alive");
            httpConnection.setRequestProperty("user-agent",
                    "ApiPOST Runtime +https://www.apipost.cn");
            
            // 是否打开输出流true|false
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            // 设置提交方法 POST|GET
            httpConnection.setRequestMethod("POST");
            // 是否使用缓存true|false
            httpConnection.setUseCaches(false);
            httpConnection.setRequestProperty("Accept-Charset", encoding);
            // 标准的HTTP POST是一种application/x-www-form-urlencoded 类型的网络表单，传递的参数都会被写入请求信息主体中
            // httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="+encoding);
            httpConnection.setRequestProperty("Content-Type", "application/json");
            
            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            httpConnection.connect();
 
            //获取URLConnection对象对应的输出流
            printWriter = new PrintWriter(httpConnection.getOutputStream());
            //发送请求参数即数据
            printWriter.print(data);
            // 输出完成后刷新并关闭流
            printWriter.flush();
            printWriter.close();
            
            // 这里返回200,则是成功调用接口，否则失败
            if(httpConnection.getResponseCode()==200){
            	// 得到响应流
            	inputStream = httpConnection.getInputStream();
            	// 处理服务器响应  (将从连接获取到输入流包装为bufferedReader)
            	bufferedReader = new BufferedReader(new InputStreamReader(inputStream,encoding)); 
            	String line;
            	// 循环读取流,若不到结尾处
            	while ((line = bufferedReader.readLine()) != null) {
            		stringBuilder.append(line);
            	}
            	//关闭流
            	bufferedReader.close(); 
            	inputStream.close();
            }else{
            	stringBuilder.append("{\"success\":\"false\",\"message\":\"调用http接口失败！\"}");
            }
            
            // 关闭连接
            httpConnection.disconnect(); 
            // 转换成json对象
            resultJson = stringBuilder.toString();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(printWriter!=null){
				printWriter.close();
			}
			if(httpConnection!=null){
				httpConnection.disconnect();
			}
		}
 
        return resultJson;
	}
}
