码迷,mamicode.com
首页 > 其他好文 > 详细

获取Cookie

时间:2018-07-25 19:00:32      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:设置   url   ams   methods   shm   要求   method   setcookie   登陆   

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

标签:设置   url   ams   methods   shm   要求   method   setcookie   登陆   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!