package com.chinacreator.video.util;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class URLUtil {

	
	/**
	 * 解读流
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static String readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = null;
		try {
			outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			byte[] data = outStream.toByteArray();
			return new String(data, "utf-8");
		} finally{
			if(outStream != null)
				outStream.close();
			if(inStream != null)
				inStream.close();
		}
	}
	
	/**
	 * 以get方式获取链接的输出
	 * @param href
	 * @return
	 * @throws Exception
	 */
	public static String get(String href, int timeout) throws Exception {
		HttpURLConnection conn = null;
		try {
            System.setProperty("sun.net.http.retryPost", "false");
			URL url = new URL(href);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			if(timeout > 0) {
				conn.setConnectTimeout(timeout);
				conn.setReadTimeout(timeout);
			}else {
                conn.setConnectTimeout(60000);
                conn.setReadTimeout(60000);
            }
			conn.addRequestProperty("content-type", "text/plain");
			conn.setUseCaches(false);
			conn.setDoOutput(false);
			return readInputStream(conn.getInputStream());
		} finally {
			if(conn != null) {
				conn.disconnect();
			}
		}
	}
	
	public static String get(String href) throws Exception {
		return get(href, 0);
	}
	
	/**
	 * 以post方式获取链接的输出
	 * @param href
	 * @return
	 * @throws Exception
	 */
	public static String post(String href, String data, int timeout, String contentType) throws Exception {
		HttpURLConnection conn = null;
		OutputStreamWriter out = null;
		if(data == null || data.length() == 0) {
			return get(href, timeout);
		} else {
			try {
				URL url = new URL(href);
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("POST");
				if(timeout > 0) {
					conn.setConnectTimeout(timeout);
					conn.setReadTimeout(timeout);
				}
				conn.addRequestProperty("content-type", contentType);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
				out.write(data);
				out.flush();
			} finally {
				if(out != null) {
					out.close();
				}
				if(conn != null) {
					conn.disconnect();
				}
			}
			if(conn != null) {
				return readInputStream(conn.getInputStream());
			}
			return null;
		}
	}
	
	public static String post(String href, String data, int timeout) throws Exception {
		return post(href, data, timeout, "text/plain");
	}
	
	public static String post(String href, String data) throws Exception {
		return post(href, data, 0);
	}
	
	public static String postJson(String href, String data) throws Exception {
		return post(href, data, 0, "application/json;charset=utf-8");
	}
	
	public static String postJson(String href, String data, int timeout) throws Exception {
		return post(href, data, timeout, "application/json;charset=utf-8");
	}
	
	public static String postForm(String href, String data, int timeout) throws Exception {
		return post(href, data, timeout, "application/x-www-form-urlencoded");
	}
	
	public static String postForm(String href, String data) throws Exception {
		return postForm(href, data, 0);
	}

	/**
	 * 把map转换为url地址
	 * @param server 项目地址
	 * @param map 存储参数的map
	 * @return  返回完整的url地址
	 */
	public static String mapToUrl(String server, Map<String,String> map){
		StringBuilder url = new StringBuilder(server);
		StringBuilder param = new StringBuilder("?");
		if (map == null) {
			return url.toString();
		}
		for(Map.Entry<String,String> entry: map.entrySet()){
			String key =  entry.getKey();
			String val =  entry.getValue();
//			if(key.equalsIgnoreCase("action")){
//				url.append(val).append(".do");
//			} else {
			param.append(key).append("=").append(val).append("&");
//			}
		}
		//删去最后的&
		if (param.toString().endsWith("&")) {
			param.deleteCharAt(param.length() - 1);
		}
		url.append(param);
		return url.toString();
	}

	/**
	 * 把map转换为url地址Params
	 * @param map 存储参数的map
	 * @return  返回完整的url地址
	 */
	public static String mapToUrl(Map<String,String> map){
		StringBuilder param = new StringBuilder("");
		if (map == null) {
			return "";
		}
		for(Map.Entry<String,String> entry: map.entrySet()){
			String key =  entry.getKey();
			String val =  entry.getValue();
			param.append(key).append("=").append(val).append("&");
		}
		//删去最后的&
		if (param.toString().endsWith("&")) {
			param.deleteCharAt(param.length() - 1);
		}
		return param.toString();
	}
	
	public static void main(String[] args) throws Exception {
		String url = "http://114.255.201.228:86/mobile-report/sendAlarmMsg.do";
		String result = postForm(url, "name=CDN_BUSINESS&content=测试短信");
		System.out.println(result);
	}
}
