获取Cookie

package com.yutong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClouderaLogin {
    public static void main(String[] args) {

        // Map<String, String> props = GetAllProperties("urls.properties");

        Map<String, String> props = GetAllProperties2("./resources/urls.properties");

        // 登陆 Url
        String loginUrl = props.get("loginUrl");
        // 需登陆后访问的 Url
        String dataUrl = props.get("dataUrl");
        String username = props.get("username");
        String password = props.get("password");

        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));

        // 模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);

        // 设置登陆时要求的信息,用户名和密码
        NameValuePair[] data = { new NameValuePair("j_username", username), new NameValuePair("j_password", password) };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode = httpClient.executeMethod(postMethod);

            // 获得登陆后的 Cookie
            Cookie[] cookies = httpClient.getState().getCookies();
            StringBuffer tmpcookies = new StringBuffer();
            for (Cookie c : cookies) {
                tmpcookies.append(c.toString() + ";");
                // System.out.println("cookies = " + c.toString());
            }
            // 用完HttpMethod就关闭
            postMethod.releaseConnection();

            if (statusCode == 302) {// 重定向到新的URL
                // System.out.println("logon success......");
                // 进行登陆后的操作
                dataUrl += new Date().getTime();
                GetMethod getMethod = new GetMethod(dataUrl);
                // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
                getMethod.setRequestHeader("cookie", tmpcookies.toString());
                httpClient.executeMethod(getMethod);
                // 打印出返回数据,检验一下是否成功

                InputStream inputStream = getMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                System.out.println(stringBuffer.toString());

                // 用完HttpMethod就关闭
                getMethod.releaseConnection();
            } else {
                System.out.println("logon fail......");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> GetAllProperties2(String path) {
        Map<String, String> map = new HashMap<String, String>();
        InputStream ins = null;
        BufferedReader reader = null;
        try {
            Resource resource = new ClassPathResource(path);
            ins = resource.getInputStream();

            reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                if (line.contains("=")) {
                    String[] keys = line.split("=");
                    map.put(keys[0], keys[1]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                    reader = null;
                }
                if (ins != null) {
                    ins.close();
                    ins = null;
                }
            } catch (IOException e) {
            }
        }
        return map;
    }

    // 读取Properties的全部信息
    public static Map<String, String> GetAllProperties(String properiesName) {
        Map<String, String> map = new HashMap<String, String>();

        InputStream is = null;
        try {
            is = ClouderaLogin.class.getClassLoader().getResourceAsStream(properiesName);
            Properties prop = new Properties();
            prop.load(is);

            map.put("loginUrl", prop.getProperty("login_url"));
            map.put("username", prop.getProperty("username"));
            map.put("password", prop.getProperty("password"));
            map.put("dataUrl", prop.getProperty("data_url"));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return map;
    }
}
不积跬步,无以至千里;不积小流,无以成江海。
原文地址:https://www.cnblogs.com/lovedaodao/p/9367601.html