Java 登录百度并获取 Cookie

package top.duanluan;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

import java.util.List;
import java.util.Set;

public class Test {

    public static void main(String[] args) throws Exception {
        String username = "";
        String password = "";

        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        // 等待后台 JS 执行
        webClient.waitForBackgroundJavaScript(10000);
        HtmlPage page = webClient.getPage("http://developer.baidu.com/");

        List<HtmlAnchor> loginAnchors = page.getByXPath("//*[@id='navbar']/ul[2]/li[2]/a");
        page = loginAnchors.get(0).click();

        // 获取用户名和密码 Input 并输入
        DomElement usernameInput = null;
        DomElement passwordInput = null;
        for (int i = 0; i < 20; i++) {
            usernameInput = page.getElementById("TANGRAM__PSP_10__userName");
            if (usernameInput != null) {
                break;
            }
            synchronized (page) {
                page.wait(500);
            }
        }
        passwordInput = page.getElementById("TANGRAM__PSP_10__password");
        usernameInput.setAttribute("value", username);
        passwordInput.setAttribute("value", password);

        // 获取并点击登录按钮
        DomElement loginBtn = page.getElementById("TANGRAM__PSP_10__submit");
        loginBtn.click();

        // 获取 Cookie
        Set<Cookie> cookies = webClient.getCookieManager().getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        }
    }
}

Java中模拟登录百度通常涉及到网络请求和HTTP协议,具体步骤如下: 1. **设置请求库**:使用如HttpURLConnection、HttpClient或更现代的第三方库如Apache HttpClient或OkHttp进行HTTP请求。 ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ``` 2. **设置User-Agent和Cookie(如果需要)**:为了模拟浏览器行为,可能需要设置合适的User-Agent和登录相关的Cookie。 ```java connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); if (cookie != null) { connection.setRequestProperty("Cookie", cookie); } ``` 3. **连接服务器并获取响应**: ```java int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 然后你可以解析响应,看是否有Set-Cookie字段来获取新的Cookie } else { System.out.println("Failed : HTTP error code : " + responseCode); } ``` 4. **登录过程**:如果需要登录,通常涉及发送POST请求,携带表单数据(如用户名和密码),可能还需要处理验证码等复杂情况。这可能需要使用`org.apache.http.client.entity.UrlEncodedFormEntity`或`OkHttp`的`Body.Builder`来构建表单数据。 5. **处理登录后的状态**:登录成功后,检查是否设置了登录状态的Cookie或Session ID,并在后续的请求中带上这些信息。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值