获取Cookie

Posted lovedaodao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取Cookie相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript单行代码,也就是代码片段

c#如何采集需要登录的页面

XSS:如何从 C# 中的字符串中删除 JS 片段?

常用python日期日志获取内容循环的代码片段

从Snipplr获取一个代码片段

java 通过HTTP请求模拟登陆,获取不到cookie,高手帮忙看一下,代码如下