package cn.com.tenlion.bigdata.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 网络请求发送
 * ClassName: HttpUtil
 * @Description: TODO
 * 创建工具: IDEA
 * 运行环境: [Tomcat7以上,MySql5.6以上,JDK7以上]
 * @author 崔宝铖
 * @date 2019年6月19日
 */
public class HttpUtil {
	
	/** 请求超时时间 */
	private static Integer TIMEOUT = 3000;
	
	/**
	 * Post请求
	 * @Description: TODO
	 * @param @param postUrl
	 * @param @param param
	 * @param @return   
	 * @return String  
	 * @throws IOException
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年6月19日
	 */
	public static String doPost(String postUrl, Map<String, Object> param) throws IOException {
		// 封装发送的请求参数
    	StringBuffer buffer = new StringBuffer();
    	int x = 0;
    	for(Entry<String, Object> map : param.entrySet()) {
    		buffer.append(map.getKey()).append("=").append(map.getValue().toString());
    		if(x != param.size()-1) {
    			buffer.append("&");
    		}
    		x++;
    	}
		URL url = new URL(postUrl);
		URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.setConnectTimeout(TIMEOUT);
        // 设置请求头属性参数
        httpUrlConnection.setRequestProperty("charset", "UTF-8"); 
        httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpUrlConnection.setRequestProperty("accept", "application/json");
        // 发送POST请求必须设置如下两行
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setDoInput(true);
        String response = "";// 响应内容
        String status = "";// 响应状态
        PrintWriter out = null;
        BufferedReader in = null;
        try{
        	// 获取URLConnection对象对应的输出流
        	out = new PrintWriter(httpUrlConnection.getOutputStream());
            // 发送请求参数
            out.write(buffer.toString());
            // flush输出流的缓冲
            out.flush();
            httpUrlConnection.connect();
            // 定义BufferedReader输入流来读取URL的响应数据
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
            // 获得URL的响应状态码
            status = new Integer(httpUrlConnection.getResponseCode()).toString();
        }catch(Exception e) {
        	e.printStackTrace();
        }finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
            	ex.printStackTrace();
            }
        }
        if(!"200".equals(status)) {
        	return null;
        }
        return response;
	} 
	
	/**
	 * Get请求
	 * @Description: TODO
	 * @param @param getUrl 请求地址
	 * @param @param param 请求参数
	 * @param @return
	 * @param @throws Exception   
	 * @return RetBody<PageData>  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年6月19日
	 */
	public static String doGet(String getUrl, Map<String, Object> param) throws Exception {
		// 封装发送的请求参数
    	StringBuffer buffer = new StringBuffer();
    	int x = 0;
    	for(Entry<String, Object> map : param.entrySet()) {
    		buffer.append(map.getKey()).append("=").append(map.getValue().toString());
    		if(x != param.size()-1) {
    			buffer.append("&");
    		}
    		x++;
    	}
		URL url = new URL(getUrl+"?"+buffer.toString());
		URLConnection urlConnection =  url.openConnection();
        HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.setConnectTimeout(TIMEOUT);
        // 设置请求头属性参数
        httpUrlConnection.setRequestProperty("charset", "UTF-8"); 
        httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpUrlConnection.setRequestProperty("accept", "application/json");
        String response = "";// 响应内容
        String status = "";// 响应状态6
        PrintWriter out = null;
        BufferedReader in = null;
        try{
        	httpUrlConnection.connect();
            // 定义BufferedReader输入流来读取URL的响应数据
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
            // 获得URL的响应状态码
            status = new Integer(httpUrlConnection.getResponseCode()).toString();
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
            }
        }
        if(!"200".equals(status)) {
        	return null;
        }
        return response;
	}
}
