gpt4 book ai didi

java - Java 类 CookieHandler 和 CookieManager 如何工作?

转载 作者:行者123 更新时间:2023-12-01 11:36:57 29 4
gpt4 key购买 nike

让我的代码以编程方式登录任何 URL 的唯一方法是使用 CookieHandler.setDefault(new CookieManager); 。这很好,但我想了解 cookie 在每个新 HttpsURLConnection 之间是如何维护的.

有人可以展示如何让下面的代码登录 Gmail 帐户而不必使用 CookieHandler.setDefault(new CookieManager); ?谢谢。

**注释:
- 替换为您自己的电子邮件和密码。
-CookieHandler.setDefault(new CookieManager);在下面的代码中被注释掉了。

public class GmailApp {

private List<String> cookies;
private HttpsURLConnection conn;

public static void main(String[] args) throws Exception {

String url = "https://accounts.google.com/ServiceLoginAuth";
String gmail = "https://mail.google.com/mail/";

GmailApp http = new GmailApp();

// CookieHandler.setDefault(new CookieManager());

String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "myemail@gmail.com", "mypassword");
http.sendPost(url, postParams);

String result = http.GetPageContent(gmail);
System.out.println(result);
}

private void sendPost(String url, String postParams) throws Exception {

URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();

int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);

BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}

private String GetPageContent(String url) throws Exception {

URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
conn.setUseCaches(false);
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}

public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {

System.out.println("Extracting form's data...");

Document doc = Jsoup.parse(html);

Element loginform = doc.getElementById("gaia_loginform");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");

if (key.equals("Email"))
value = username;
else if (key.equals("Passwd"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}

StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}

public void setCookies(List<String> cookies) {
this.cookies = cookies;
}

}

最佳答案

当您通过 java.net.CookieHandler.setDefault() 静态设置默认 CookieHandler 时,当前和 future 的 HttpURLConnection(通过其底层 HTTP 客户端类)将检查此默认 cookie 处理程序是否存在,找到它后将使用它来检索请求的 cookie,并存储设置/返回的新 cookie。只要您想在所有请求中维护 cookie,这就会提供一个静态 cookie-jar。请务必设置所需的 CookiePolicy,否则 java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER 为默认值。

请注意,您的代码存在一些问题:

cookie.split(";", 1)[0]

这个分割不会做任何事情,如果你想从第一个分号截断字符串,你需要 cookie.split(";", 2)[0] (1->2)从此。

此外,您仅在 GET 请求后调用 setCookies - 您还需要捕获 POST 登录响应中的 cookie。

关于java - Java 类 CookieHandler 和 CookieManager 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873713/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com