package com.zzsn.search.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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GetCookies {

    public static String sendGetRealUrl(String url) {
        String result = "";
        String urlName = url;
        try {
            URL realURL = new URL(urlName);
            URLConnection conn = realURL.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            for (String s : map.keySet()) {
                if(s!=null && s.contains("Location")){
                    if(map.get(s).size()>0){
                        result=map.get(s).get(0);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String sendGet(String url) {
        String result = "";
        String urlName = url;
        try {
            URL realURL = new URL(urlName);
            URLConnection conn = realURL.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            for (String s : map.keySet()) {
                System.out.println(s + "-->" + map.get(s));
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
  
    public static String sendPost(String url,String param){
        String result = "";
        HttpURLConnection conn = null;  
        try {
            URL realUrl = new URL(url);
            conn =    (HttpURLConnection) realUrl.openConnection();
             
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            conn.setInstanceFollowRedirects(true);
             
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //post设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);//这一行必须要写，因为要将参数放在outputStream中输出
            //PrintWriter out = new PrintWriter(conn.getOutputStream());
            //out.print(param);
            PrintWriter out =new PrintWriter(conn.getOutputStream());
            //out.write(param);
            out.print(param);  //写入缓存
            out.flush();
                    
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));// 发送请求参数
            String line;
            while((line = in.readLine()) != null){
                result +="\n" + line;
                    }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param encode
     *            请求页面的字符编码
     * @param cookie
     *            cookie
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost1(String url, String param, String encode,String cookie) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
            conn.setRequestProperty("Cache-Control","max-age=0");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Cookie",cookie);
            //conn.setRequestProperty("Host","www.zjtax.gov.cn");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),encode));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 获取cookie
     *
     * @param url
     *            发送请求的URL
     * @return key=value;key=value;...
     */
    public static Map<String,String> getCookie2(String url) {
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setRequestProperty("Accept-Encoding","gzip, deflate, sdch");
            conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
            conn.setRequestProperty("Cache-Control","max-age=0");
            conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("Host","www.zjtax.gov.cn");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //是否自动执行 http 重定向，默认为true
            //如果实际操作中，不存在重定向问题，不需要设置此行。
            conn.setInstanceFollowRedirects(false);

            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sessionId = "";
        String cookieVal = "";
        String key = null;

//      Map<String,List<String>> map = conn.getHeaderFields();
//      for (String key1 : map.keySet()) {
//          System.out.println(key1 + "--->" + map.get(key1));
//      }
        //取cookie
        Map<String,String> map=new HashMap<>();
        for(int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++){
            if(key.equalsIgnoreCase("set-cookie")){
                cookieVal = conn.getHeaderField(i);
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                if(cookieVal.contains("SUID")||cookieVal.contains("SNUID")){
                    String keys = cookieVal.substring(0,cookieVal.indexOf("="));
                    String val = cookieVal.substring(cookieVal.indexOf("=")+1);
                    map.put(keys,val);
                }
            }
        }
        //如果实际操作中，不存在重定向问题，不需要以下四行
//        String location= conn.getHeaderField("Location");//获取 重定向地址
//        List<String> list = getCookie3(location,sessionId);
//        List<String> list2 = getCookie3(list.get(1),sessionId+list.get(0));
//        sessionId = sessionId + list2.get(0);

        return map;
    }
    /**
     * 获取 cookie
     * @param url
     *          发送请求的URL
     * @param cookie
     *          cookie
     */
    public static List<String> getCookie3(String url,String cookie) {
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setRequestProperty("Accept-Encoding","gzip, deflate, sdch");
            conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
            conn.setRequestProperty("Cache-Control","max-age=0");
            conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("Host","www.zjtax.gov.cn");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Cookie",cookie);

            conn.setInstanceFollowRedirects(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sessionId = "";
        String cookieVal = "";
        String key = null;
        String location= conn.getHeaderField("Location");

        for(int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++){
            if(key.equalsIgnoreCase("set-cookie")){
                cookieVal = conn.getHeaderField(i);
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                sessionId = sessionId + cookieVal + ";";
            }
        }
        List<String> list = new ArrayList<String>();
        list.add(sessionId);//存放cookie
        list.add(location);//存放重定向地址
        return list;
    }

     
}
