首页 > 其他 > 详细

获取Cookie

时间:2018-07-25 18:43:32      阅读:169      评论:0      收藏:0      [点我收藏+]
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;

import java.util.HashMap;
import java.util.Map;

public class CookieUtil {

    public static void main(String[] args) {
        // 登陆 Url
        String loginUrl = "http://www.xxx.yyy.zzz";

        Map<String, String> params = new HashMap<>();
        params.put("userid", "admin");
        params.put("pwd", "admin");

        Cookie[] cookies = getCookie(loginUrl, params);
        StringBuffer tmpcookies = new StringBuffer();
        for (Cookie c : cookies) {
            tmpcookies.append(c.toString() + ";");
            System.out.println(c.getName() + "----" + c.getValue());
        }
    }

    public static Cookie[] getCookie(String loginUrl, Map<String, String> params) {
        HttpClient httpClient = new HttpClient();
        try {
            // 模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式
            PostMethod postMethod = new PostMethod(loginUrl);
            // 设置登陆时要求的信息,用户名和密码
            NameValuePair[] data = new NameValuePair[params.size()];

            int index = 0;
            for (String key : params.keySet()) {
                data[index] = new NameValuePair(key, params.get(key));
                index++;
            }

            postMethod.setRequestBody(data);

            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode = httpClient.executeMethod(postMethod);

            // 获得登陆后的 Cookie
            Cookie[] cookies = httpClient.getState().getCookies();

            return cookies;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Cookie[]{};
    }
}

 

获取Cookie

原文:https://www.cnblogs.com/lovedaodao/p/9367601.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!