package cn.pluss.platform.wap;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author yuchen
 * 
 * @Description 
 */
public class HttpUrlConnection {
			
	/**
	 * 
	 * httpXML:(向微信发起统一下单请求  得到对应的返回值 ). <br/> 
	 * 
	 * @author Administrator 
	 * @param url
	 * @param xml
	 * @return 
	 * @since JDK 1.8
	 */
	public static String httpXML(String url, String xml) {
		String result = null;
		try {
			InputStream is = httpPostXML(url, xml);
			BufferedReader in = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			result = buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}
 
	private static InputStream httpPostXML(String url, String xml) {
		InputStream is = null;
		PrintWriter out = null;
		try {
			URL u;
			u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setConnectTimeout(20000);
			conn.setReadTimeout(50000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			OutputStreamWriter outWriter = new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8");
			out = new PrintWriter(outWriter);
			out.print(xml);
			out.flush();
			out.close();
			is = conn.getInputStream();
		} catch (Exception e) {
 
			e.printStackTrace();
		}
		return is;
	}
	
	/**
	 * 
	 * convertRequestParamsToMap:(将request中的参数转换成Map 已测试 可用). <br/> 
	 * 
	 * @author Administrator 
	 * @param request
	 * @return 
	 * @since JDK 1.8
	 */
    public static Map<String, Object> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<>();
        Set<Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        for (Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }
	
	
}

