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 2016年5月19日 下午6:05:53
 */
public class HttpUtils {

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

	/**
	 * 默认http连接超时时间（单位：ms）
	 */
	public static final int HTTP_CONNECT_TIMEOUT = 5000;
	
	
	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();
		OutputStream outputStream = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection httpUrlConn = 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 = httpUrlConn.getOutputStream();
				outputStream.write(postData.getBytes("UTF-8"));
				
			}
			//将返回的输入流转换成字符串
			inputStream = httpUrlConn.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			for(String str = null; (str = bufferedReader.readLine()) != null;){
				buffer.append(str);
			}
			
			jsonObject = JSONObject.parseObject(buffer.toString());
		}catch (Exception e) {
			logger.error("https request error:{}", e);
		}finally{
			try {
				if(httpUrlConn!=null){
					httpUrlConn.disconnect();
					httpUrlConn=null;
				}
			} catch (Exception e) {}
			try {
				if(outputStream!=null){
					outputStream.close();
					outputStream=null;
				}
			} catch (IOException e) {}
			try {
				if(inputStreamReader!=null){
					inputStreamReader.close();
					inputStreamReader = null;
				}
			} catch (IOException e) {}
			try {
				if(inputStream!=null){
					inputStream.close();
					inputStream = null;
				}
			} catch (IOException e) {}
			try {
				if(bufferedReader!=null){
					bufferedReader.close();
					bufferedReader = null;
				}
			} catch (IOException e) {}
		}
		return jsonObject;
	}
	
	private 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;
	}
	
}
