我想编写一个Java应用程序,它登录到一个网站,然后通过cookie身份验证导航到不同的站点。 我已经设法登录网站并检索它的代码。 第一个问题:
在循环HeaderFieldKeys时没有“Set-Cookie”键,只有:Date,Server,X-Powered-By,Expires,Last-Modified,Cache-Control,Cache-Control,Pragma,X- UA兼容,X帧选项,严格传输安全,变化,连接,传输编码和内容类型。
正如您在我的代码中看到的,我尝试了另一个代码来检索cookie,这有效。现在有了我想要导航到网站的另一个链接的cookie,但它不起作用。
package myEDKS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class SpielHelfer
{
public static HttpCookie cookieW;
public static String cookieV;
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
try
{
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("https://www.w-da.net/wws/109580.php?sid=41853050108060779043427902790460");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("login_login=********");
ps.print("&login_password=********");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies = cookieJar.getCookies();
for (HttpCookie cookie: cookies)
{
System.out.println("CookieHandler retrieved cookie: " + cookie);
cookieW = cookie;
String cookieC = cookie.getValue();
int x = cookieC.length();
cookieV = cookieC;
System.out.println("**************************************");
}
}
catch(Exception e)
{
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
System.out.println(cookieW);
try
{
URL url2 = new URL("https://www.w-da.net/wws/109580.php?sid=41853050108060779043427902790460");
URLConnection con2 = url2.openConnection();
con2.setRequestProperty("Cookie", cookieV);
con2.connect();
BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream()));
String line2 = null;
while ((line2 = in2.readLine()) != null)
{
System.out.println(line2);
}
}
catch(Exception e)
{
System.out.println("Unable to set cookie using CookieHandler");
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我不擅长Java,但我建议尝试使用Selenium Webdriver。因为它可以帮助您以更高的方式浏览网站。它包含了所有您需要的功能的漂亮API。因为用这种方式写它会很长很难。