package com.sysu.admin.utils.http;

import okhttp3.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
	/**
	 * 提供post 重定向的方法 (该方法只可用于web端)
	 * @param url
	 * @param response
	 * @param parameter
	 * @throws IOException
	 */
	public static void sendByPost(String url, HttpServletResponse response, Map<String, String> parameter) {
		response.setContentType("text/html");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println(" <HEAD><TITLE>sender</TITLE></HEAD>");
		out.println(" <BODY>");
		out.println("<form name=\"submitForm\" action=\"" + url + "\" method=\"post\">");
		if(parameter!=null) {
			Iterator<String> it = parameter.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				String val = parameter.get(key);
				if(val != null && !val.isEmpty()) {
					out.println("<input type=\"hidden\" name=\"" + key + "\" value=\"" + val + "\"/>");
				}
			}
		}
		out.println("</from>");
		out.println("<script>window.document.submitForm.submit();</script> ");
		out.println(" </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	
	/**
	 * 用传统的URI类进行请求
	 * 
	 * @param urlStr
	 */
	public static String httpPost(String urlStr,String xmlInfo) {
		try {
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			con.setDoOutput(true);
			con.setRequestProperty("Content-Type", "text/xml");


			OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
			out.write(xmlInfo);
			out.flush();
			out.close();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			StringBuffer line = new StringBuffer();
			while(br.ready()) {
				line.append(br.readLine());
			}
			return line.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * map 转 xml字符串
	 * @param map
	 * @return
	 */
    public static String mapToXml(Map<String, String> map) {
        Document d = DocumentHelper.createDocument();
        Element root = d.addElement("xml");
        Set<String> keys = map.keySet();
        for(String key:keys) {
        	
            root.addElement(key).addCDATA(map.get(key));

        }
        StringWriter sw = new StringWriter();
        XMLWriter xw = new XMLWriter(sw);
        xw.setEscapeText(false);
       
        try {
			xw.write(d);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return sw.toString();
    }
	
    
    /**
     * 同步访问
     * @param address
     * @param paramsMap
     * @return
     */
    public  static String httpPost2(String address, Map<String,String> paramsMap) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        FormBody.Builder builder = new FormBody.Builder();
        if (paramsMap!=null) {
            for (String key : paramsMap.keySet()) {
                builder.add(key, paramsMap.get(key));
            }
        }
        RequestBody requestBody=builder.build();
        Request request = new Request.Builder()
                .url(address).post(requestBody)
                .build();
        try {
            Response response=  client.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }else{
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 同步访问
     * @param address
     * @return
     */
    public  static String httpGet(String address) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .url(address).get()
                .build();
        try {
            Response response=  client.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }else{
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	

	
	


}
