我尝试登录网站并在使用java URLConnection登录网站后获取网页的网页源代码。我面临的问题是我无法维护会话,所以服务器给了我这个警告,并且不让我联系:
此系统需要使用HTTP cookie来验证授权信息。 我们的系统检测到您的浏览器已禁用HTTP cookie,或者不支持HTTP cookie。 有关如何正确配置浏览器以与此系统配合使用的更多信息,请参阅浏览器中的“帮助”页面。
起初我正在尝试发送空cookie以让服务器了解我正在处理会话,但它也没有给我会话ID。
这是我的源代码:
try {
// Construct data
String data = URLEncoder.encode("usr", "UTF-8") + "=" + URLEncoder.encode("usr", "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("pass", "UTF-8");
// Send data
URL url = new URL("https://loginsite.com");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Cookie", "SESSID=");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
String headerName=null;
for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
System.out.println(cookie.split(";", 2)[0]);
}
}
} catch (Exception e) {
}
答案 0 :(得分:0)
您应该使用HTTP库来处理会话管理和HTTP协议的其他详细信息,例如:开箱即用支持Cookies和Keep-Alive,Proxies等。试试Apache HttpComponents