Java後臺獲取Cookie

Cookie概念:Cookie服務器發送給瀏覽器的一小段文本信息java

Java後臺獲取Cookie正常操做:web

Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
     for (Cookie cookie : cookies){
         return cookie.getName() + " " + cookie.getValue();
     }
 }       

可是,只能獲取本身域裏的cookie,即localhost域下的Cookie,沒法獲取其餘域裏的Cookie。chrome

獲取其餘域裏的Cookie:apache

1.經過瀏覽器開發者模式查看相應域裏的Cookie,經過Cookie獲取值;瀏覽器

2.經過HttpClient向服務器發送登陸請求,獲取相應結果裏的Set-Cookie,下次向服務器發送請求時帶上Cookie;服務器

3.經過WebMagic框架selenium模擬瀏覽器實現登錄cookie

方法二案例:app

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @auther mxh
 * @time 2019/5/20 13:48
 */
public class ZhiHuTest {

    public static void main(String[] args) throws java.text.ParseException {
        String name = "******@qq.com"; //
        String password = "******"; //

        // 全局請求設置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        // 建立cookie store的本地實例
        CookieStore cookieStore = new BasicCookieStore();
        // 建立HttpClient上下文
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        // 建立一個HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();

        CloseableHttpResponse res = null;

        // 建立本地的HTTP內容
        try {
            try {
                // 建立一個get請求用來獲取必要的Cookie,如_xsrf信息
                HttpGet get = new HttpGet("http://www.zhihu.com/");

                res = httpClient.execute(get, context);
                // 獲取經常使用Cookie,包括_xsrf信息
                System.out.println("訪問知乎首頁後的獲取的常規Cookie:===============");
                for (Cookie c : cookieStore.getCookies()) {
                    System.out.println(c.getName() + ": " + c.getValue());
                }
                res.close();

                // 構造post數據
                List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
                valuePairs.add(new BasicNameValuePair("email", name));
                valuePairs.add(new BasicNameValuePair("password", password));
                valuePairs.add(new BasicNameValuePair("remember_me", "true"));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
                entity.setContentType("application/x-www-form-urlencoded");

                // 建立一個post請求
                HttpPost post = new HttpPost("https://www.zhihu.com/login/email");
                // 注入post數據
                post.setEntity(entity);
                res = httpClient.execute(post, context);

                // 打印響應信息,查看是否登錄是否成功
                System.out.println("打印響應信息===========");
                System.out.println(res.toString());
                res.close();

                System.out.println("登錄成功後,新的Cookie:===============");
                for (Cookie c : context.getCookieStore().getCookies()) {
                    System.out.println(c.getName() + ": " + c.getValue());
                }

                // 構造一個新的get請求,用來測試登陸是否成功
                HttpGet newGet = new HttpGet("https://www.zhihu.com/question/293207596/answer/684673400");
                res = httpClient.execute(newGet, context);
                String content = EntityUtils.toString(res.getEntity());
                System.out.println("登錄成功後訪問的頁面===============");
                System.out.println(content);
                res.close();

            } finally {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

上述代碼,只要網站登錄登陸過程不是太繁瑣,如須要驗證則不太實用框架

方案三實現代碼:post

// 自動登錄方法
    public void login() {
        //註冊chrome
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://login.jiayuan.com/?refrer=http://www.jiayuan.com&host=0");// 打開網址
        // 防止頁面未能及時加載出來而設置一段時間延遲
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 設置用戶名密碼
        driver.findElement(By.id("login_email")).sendKeys("15735400536"); // 用戶名
        driver.findElement(By.id("login_password")).sendKeys("mxh970923"); // 密碼
        // 模擬點擊   //form[@id='form-group-login']/button
        driver.findElement(By.xpath("//*[@id=\"login_btn\"]"))
                .click(); // xpath語言:id爲form-group-login的form下的button

        // 防止頁面未能及時加載出來而設置一段時間延遲
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 獲取cookie信息
        cookies = driver.manage().getCookies();

        driver.close();
    }
相關文章
相關標籤/搜索