使用Java中的cookies登录网页

3
我想从需要用户名和密码的网页下载文件,但首先我必须获取cookies。这个Python脚本完全描述了我想做的事情,但我想使用Java来实现。
我已经了解了httpclient库,并在此进行了阅读。httpclient是我所需要的全部吗?是否有机制相当于Java中的mechanize和urllib2?
谢谢您提前。
#!/usr/bin/python

import mechanize, urllib2
from urllib import urlopen, urlencode 

user = 'username'
password = 'password'
output_file = 'name.pdf'

web = "https://..."
bills_page = "https://.../bills"
login_web = "https://.../login/"
file = "https://.../file_I_want"

br = mechanize.Browser()
br.open(web)

data = {
    'user_username': user,
    'user_password': password,
    'idClientehidden': '',
    'answer': ''
}

response1 = urllib2.Request(login_web, urlencode(data))

br.open(response1)
br.open(bills_page)
html_bills = br.response().read()

br.open(file)
pdf_bill = open(output_file, 'w')
pdf_bill.write(br.response().read())
pdf_bill.close()

你的问题只是关于读取 cookies 吗?还是你正在寻找登录外部网站并下载文件的方法? - Yogendra Singh
外部网站登录并下载文件的方法。我的问题是,我是否必须使用httpclient,或者您是否知道对于我的目标有更好的选择。 - jav_000
1个回答

3

HttpClient 是一个处理 cookies 和访问授权 URL 的好框架。

或者,您可以使用核心 Java 组件,例如下面的 AuthenticatorURLBufferedReader

  1. Create a custom Authenticator which will read userId/Password from the cookie

    public class HTTPAuthenticator extends Authenticator {
    
      protected PasswordAuthentication getPasswordAuthentication() {
         String username = "user"; //<--read from cookie
         String password = "password"; //<--read from cookie
         return new PasswordAuthentication(username, password.toCharArray());
      }
    }
    
  2. Set your custom authenticator HTTPAuthenticator as default Authenticator.

    Authenticator.setDefault(new HTTPAuthenticator());
    
  3. Once done, read the files and write in your local drive as below:

    URL url = new URL("http://secureweb/secure.html");
    BufferedReader br= new BufferedReader(new InputStreamReader(url.openStream()));
    File file = new File("myLocalFile");
    BufferedWriter bw = new BufferedWriter (file);
    String lineStr;
    while ((str = br.readLine()) != null) {
         bw.write();
    }
    bw.close();
    br.close();
    
希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接