package com.nbclass.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * HTTP请求工具类
 * @author Leon
 * @datetime 2019年4月22日 下午9:19:50
 */
public class HttpUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	/**
	 * 默认http连接超时时间（单位：ms）
	 */
	public static final int HTTP_CONNECT_TIMEOUT = 15000;

	public static JSONObject httpGet(String requestUrl){
		return httpGet(requestUrl, null);
	}
	
	public static JSONObject httpGet(String requestUrl, String postData){
		return httpRequest(requestUrl, "GET", postData);
	}
	
	public static JSONObject httpPost(String requestUrl){
		return httpPost(requestUrl, null);
	}
	
	public static JSONObject httpPost(String requestUrl, String postData){
		return httpRequest(requestUrl, "POST", postData);
	}
	
	private static JSONObject httpRequest(String requestUrl, String requestMethod, String postData) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		InputStream inputStream = null;
		try{
			postData = formatPostData(postData);
		//	logger.info("httpRequestUrl: "+requestUrl+", postData: "+postData);
			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			//设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod)){
				httpUrlConn.connect();
			}
			//当有数据需要提交时
			if (postData != null){
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(postData.getBytes("UTF-8"));
				outputStream.close();
				outputStream=null;
			}
			//将返回的输入流转换成字符串
			inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			for (String str = null; (str = bufferedReader.readLine()) != null;)buffer.append(str);

			bufferedReader.close();
			inputStreamReader.close();
			bufferedReader = null;
			inputStreamReader = null;
			jsonObject = JSONObject.parseObject(buffer.toString());
		}catch (Exception e) {
			e.printStackTrace();
			logger.error("https request error:{}", e);
		} finally {
			buffer = null;
			if(httpUrlConn!=null){
				httpUrlConn.disconnect();
				httpUrlConn=null;
			}
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				inputStream = null;
			}
		}
		return jsonObject;
	}
	
	protected static String formatPostData(String strdata){
		String result = strdata;
		try {
			JSONObject jsonObject = JSONObject.parseObject(strdata);
			if(jsonObject != null){
				result = "";
				for (Entry<String, Object> entry : jsonObject.entrySet()) {
		            if(StringUtils.isBlank(result)){
		            	result = entry.getKey() + "=" + entry.getValue();
		            }else{
		            	result += "&" + entry.getKey() + "=" + entry.getValue();
		            }
		        }
			}
		} catch (Exception e) {
		}
		return result;
	}
	
}
