package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import static com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver.iterator;

public class HttpUtil {

	public static String doGet(String geturl, String params,Map headerparam) {
		String realUrl = geturl + "?" + params;
		System.out.println(realUrl);

		try {
			// 1.通过�? URL 上调�? openConnection 方法创建连接对象
			URL url = new URL(realUrl);
			URLConnection conn = url.openConnection();

			// 2.处理设置参数和一般请求属�?
			// 2.1设置参数
			// 可以根据请求的需要设置参�?
			conn.setUseCaches(false);
			conn.setConnectTimeout(5000); // 请求超时时间

			// 2.2请求属�??
			// 设置通用的请求属�? 更多的头字段信息可以查阅HTTP协议
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");

			conn.setRequestProperty("contentType", "UTF-8");

			if(headerparam != null){
				Set<String> keys =headerparam.keySet();
				Iterator<String> iterator = keys.iterator();
				while(iterator.hasNext()){
					String key =iterator.next().toString();
					String value = headerparam.get(key).toString();
					conn.setRequestProperty(key,value);
				}
			}



			// 3.使用 connect 方法建立到远程对象的实际连接�?
			conn.connect();

			// 4.远程对象变为可用。远程对象的头字段和内容变为可访问�??
			// 4.1获取响应的头字段
			Map<String, List<String>> headers = conn.getHeaderFields();
			System.out.println(headers); // 输出头字�?

			// 4.2获取响应正文
			BufferedReader reader = null;
			StringBuffer resultBuffer = new StringBuffer();
			String tempLine = null;

			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}
			// System.out.println(resultBuffer);
			reader.close();
			return resultBuffer.toString();
		} catch (MalformedURLException e) {
			// TODO 自动生成�? catch �?
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成�? catch �?
			e.printStackTrace();
		} finally {

		}
		return null;

	}

	public static String doPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连�?
			URLConnection conn = 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("contentType", "UTF-8");
			// 发�?�POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发�?�请求参�?
			out.print(param);
			System.out.println(param + "##################################");
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响�?
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "/n" + line;
			}
		} catch (Exception e) {
			System.out.println("发�?�POST请求出现异常�?" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流�?�输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String getOsAndBrowserInfo(HttpServletRequest request) {
		String browserDetails = request.getHeader("User-Agent");
		String userAgent = browserDetails;
		String user = userAgent.toLowerCase();

		String os = "";
		String browser = "";

		// =================OS Info=======================
		if (userAgent.toLowerCase().indexOf("windows") >= 0) {
			os += "Windows";
		}
		if (userAgent.toLowerCase().indexOf("micromessenger") >= 0) {
			os += "weixin";
		}
		if (userAgent.toLowerCase().indexOf("mac") >= 0) {
			os += "Mac";
		}
		if (userAgent.toLowerCase().indexOf("x11") >= 0) {
			os += "Unix";
		}
		if (userAgent.toLowerCase().indexOf("android") >= 0) {
			os += "Android";
		}
		if (userAgent.toLowerCase().indexOf("iphone") >= 0) {
			os += "IPhone";
		}
		{
			os += "UnKnown, More-Info: " + userAgent;
		}
		// ===============Browser===========================
		if (user.contains("edge")) {
			browser = (userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-");
		} else if (user.contains("msie")) {
			String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
			browser = substring.split(" ")[0].replace("MSIE", "IE") + "-" + substring.split(" ")[1];
		} else if (user.contains("safari") && user.contains("version")) {
			browser = (userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0] + "-"
					+ (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
		} else if (user.contains("opr") || user.contains("opera")) {
			if (user.contains("opera")) {
				browser = (userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0] + "-"
						+ (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
			} else if (user.contains("opr")) {
				browser = ((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-"))
						.replace("OPR", "Opera");
			}

		} else if (user.contains("chrome")) {
			browser = (userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
		} else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1)
				|| (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1)
				|| (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1)) {
			browser = "Netscape-?";

		} else if (user.contains("firefox")) {
			browser = (userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
		} else if (user.contains("rv")) {
			String IEVersion = (userAgent.substring(userAgent.indexOf("rv")).split(" ")[0]).replace("rv:", "-");
			browser = "IE" + IEVersion.substring(0, IEVersion.length() - 1);
		} else {
			browser = "UnKnown, More-Info: " + userAgent;
		}

		return os + " --- " + browser;
	}

	public static String getIPAddress(HttpServletRequest request) {
		String ip = null;

		//X-Forwarded-For：Squid 服务代理
		String ipAddresses = request.getHeader("X-Forwarded-For");

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//Proxy-Client-IP：apache 服务代理
			ipAddresses = request.getHeader("Proxy-Client-IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//WL-Proxy-Client-IP：weblogic 服务代理
			ipAddresses = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//HTTP_CLIENT_IP：有些代理服务器
			ipAddresses = request.getHeader("HTTP_CLIENT_IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//X-Real-IP：nginx服务代理
			ipAddresses = request.getHeader("X-Real-IP");
		}

		//有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
		if (ipAddresses != null && ipAddresses.length() != 0) {
			ip = ipAddresses.split(",")[0];
		}

		//还是不能获取到，最后再通过request.getRemoteAddr();获取
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("accessId","1625205696412");
		map.put("stringToSign","4ab54dea9926f3386b56fd5fe51b35ae0fe1405a");

		String r =doGet("http://127.0.0.1:88/api/test/sfz","",map);
		System.out.println(r);
	}

}
