package com.unis.base.common.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

@Slf4j
public class HttpRequestUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);

	/**
	 * 向指定URL发送GET方法的请求
	 * @param url 发送请求的URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		//记录缓冲数据
		StringBuffer sb = null;
		sb=new StringBuffer();
		//缓冲输入流
		BufferedReader in = null;
		//请求URL地址
		URL realUrl=null;
		//URL之间的连接对象
		HttpURLConnection conn=null;
		String line=null;
		//头信息的map
		//Map<String, List<String>> map=null;
		String urlNameString=null;
		if(param!=null&&param.length()>0){
			urlNameString = url + "?" + param;
		}else{
			urlNameString=url;
		}
		String res=null;
		try {
			realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			conn = (HttpURLConnection)realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			//模拟成ie6.0
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
			conn.setUseCaches(false);
			// 建立实际的连接
			conn.connect();
			// 获取所有响应头字段
            /*map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }*/
			// 根据ResponseCode判断连接是否成功
			int responseCode = conn.getResponseCode();
			if(responseCode==HttpStatus.OK.value()){
				// 定义 BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}
				res= sb.toString();
			}else{
				log.error("code:{}   request:{}   参数:{}   响应错误:{}",responseCode,url,param,conn.getResponseMessage());
			}
		} catch (IOException e) {
			log.error("request:{}   参数:{}   发送请求异常:{}",url,param,e.getMessage());
		}
		//使用finally块来关闭输入流
		finally {
			conn.disconnect();
			log.debug("request:{}   res:{}" , url,res);
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		return res;
	}

	/**
	 * 向指定 URL 发送POST方法的请求,参数为json格式
	 * @param url 发送请求的 URL
	 * @param  jsonStr 请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendJSON(String url, String jsonStr) {
		PrintWriter out = null;
		//缓冲输入流
		BufferedReader in = null;
		//请求URL地址
		URL realUrl=null;
		//URL之间的连接对象
		HttpURLConnection conn=null;
		String line=null;
		//记录缓冲数据
		StringBuffer sb = null;
		sb=new StringBuffer();
		String res=null;
		try {
			realUrl = new URL(url);
			// 打开和URL之间的连接
			conn = (HttpURLConnection)realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
			conn.setUseCaches(false);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
			// 发送请求参数
			out.write(jsonStr);
			// flush输出流的缓冲
			out.flush();

			int responseCode = conn.getResponseCode();
			if(responseCode== HttpStatus.OK.value()){
				// 定义BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}
				res=sb.toString();
			}else{
				log.error("code:{}   request:{}   参数:{}   响应错误:{}",responseCode,url,jsonStr,conn.getResponseMessage());
			}
		} catch (Exception e) {
			log.error("request:{}   参数:{}   发送请求异常:{}",url,jsonStr,e);
		}
		//使用finally块来关闭输出流、输入流
		finally{
			log.debug("request:{}   res:{}", url,res);
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return res;
	}
	
	 public static String doFormPost(String url, Map<String, Object> params) {  
	        URL u = null;  
	        HttpURLConnection con = null;  
	        // 构建请求参数  
	        StringBuffer sb = new StringBuffer();  
	        if (params != null) {  
	            for (Entry<String, Object> e : params.entrySet()) {  
	                sb.append(e.getKey());  
	                sb.append("=");  
	                sb.append(e.getValue());  
	                sb.append("&");  
	            }  
	            sb.substring(0, sb.length() - 1);  
	        }  
	        System.out.println("send_url:" + url);  
	        System.out.println("send_data:" + sb.toString());  
	        // 尝试发送请求  
	        try {  
	            u = new URL(url);  
	            con = (HttpURLConnection) u.openConnection();  
	            //// POST 只能为大写，严格限制，post会不识别  
	            con.setRequestMethod("POST");  
	            con.setDoOutput(true);  
	            con.setDoInput(true);  
	            con.setUseCaches(false);  
	            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
	            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");  
	            osw.write(sb.toString());  
	            osw.flush();  
	            osw.close();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            if (con != null) {  
	                con.disconnect();  
	            }  
	        }  
	  
	        // 读取返回内容  
	        StringBuffer buffer = new StringBuffer();  
	        try {  
	            //一定要有返回值，否则无法把请求发送给server端。  
	            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));  
	            String temp;  
	            while ((temp = br.readLine()) != null) {  
	                buffer.append(temp);  
	                buffer.append("\n");  
	            }  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  
	        return buffer.toString();  
	    }  
}