package com.dcit.common.utils;

import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
* <p>Title: HttpUtil</p>
* <p>Description: http请求工具类</p>
* <p>Company: SJZ DC-IT co. LTD</p> 
* @author ZZZ
* @date 2018年8月29日 下午5:09:09
 */
public class HttpUtil {
	
	/**
	 * 获取IP（如果是多级代理，则得到的是一串IP值）
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if (ip != null && ip.length() > 0) {
			String[] ips = ip.split(",");
			for (int i = 0; i < ips.length; i++) {
				if (!"unknown".equalsIgnoreCase(ips[i])) {
					ip = ips[i];
					break;
				}
			}
		}

		return ip;
	}
	
	/**
	 * 初始化HTTP头
	 * @return
	 */
	public static HttpHeaders initHttpHeaders() {
		HttpHeaders headers = new HttpHeaders();
		MediaType mediaType = new MediaType("text", "html",
				Charset.forName("utf-8"));
		headers.setContentType(mediaType);
		return headers;
	}
	
	/**
	 * 返回服务器地址 like http://127.0.0.1:8881/XXX/
	 * @param request
	 * @return
	 */
	public static String getHostUrl(HttpServletRequest request) {
		String hostName = request.getServerName();
		Integer hostPort = request.getServerPort();
		String path = request.getContextPath();

		if (hostPort == 80) {
			return "http://" + hostName + path + "/";
		} else {
			return "http://" + hostName + ":" + hostPort + path + "/";
		}
	}

	/**
	 * 获取当前的website路径 String
	 * @param request
	 * @return
	 */
	public static String getWebSite(HttpServletRequest request) {
		String returnUrl = request.getScheme() + "://"
				+ request.getServerName();

		if (request.getServerPort() != 80) {
			returnUrl += ":" + request.getServerPort();
		}

		returnUrl += request.getContextPath();

		return returnUrl;
	}

}
