首页 > 解决方案 > 通过身份验证将 pdf 内容在线传输到 BufferedInputStream

问题描述

我一直在尝试阅读在浏览器中打开的 pdf 的内容 - 没有成功。我在网上找到的所有示例都需要这一步:

    URL url = new URL(strURL);
    BufferedInputStream file = new BufferedInputStream(url.openStream());
    PDFParser parser = new PDFParser(file);

问题是我必须首先在站点中进行身份验证 - 然后导航到 pdf 位置 - 在新选项卡上打开 - 然后我切换到选项卡并获取 url。

但是,当我将 url 传递给上面的代码时 - 它正在创建一个新请求,因此它失去了身份验证并且站点返回 code 401-Unauthorized

一个重要的细节 - 这是一个嵌入式 pdf。

有没有我可以使用的解决方法 - 例如抓取已经加载的 pdf - 而不是拨打新电话?我没主意了。谢谢!

编辑

我想到的一种可能的解决方法是在 Chrome 上打开此设置

Download PDF files instead of automatically opening them in Chrome    On/Off

是否可以以编程方式打开此设置?请注意,我打开了设置 - 在我的 Chrome 配置文件上也Selenium使用了 - 但是当 Selenium 浏览器打开时,此设置被关闭。

这可以通过添加选项来解决:

ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=<path_to_profile>");
driver = new ChromeDriver(options);

更新

Abhishek Dhoundiyal的回答很棒——我唯一改变的就是——因为我在导航到特定页面时已经通过了身份验证——而不是再次传递用户名和密码——我只是保存了 cookie 并将它们加载到 url:

Set<Cookie> allCookies = driver.manage().getCookies();

然后,

URL url = new URL(strUrl);
HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();

for(Cookie cookie : allCookies) {
   myURLConnection.setRequestProperty("Cookie", cookie.toString());
}

myURLConnection.setRequestMethod("GET");
BufferedInputStream file = new BufferedInputStream(myURLConnection.getInputStream());

最后对 pdf 做一些事情,即:获取文本。

标签: javaseleniumpdfselenium-chromedriver

解决方案


为避免401-Unauthorized,您需要传递您的用户凭据。

    URL url = new URL("YOUR_URL");

    HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();
    String userCredentials = "username:password";
    String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());
    myURLConnection.setRequestProperty ("Authorization", basicAuth);
    myURLConnection.setRequestMethod("GET");

    BufferedInputStream file = new BufferedInputStream(myURLConnection.getInputStream());
    PDFParser parser = new PDFParser(file);

启用下载

    ChromeOptions options = new ChromeOptions();
    Map<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("download.prompt_for_download", false);
    prefs.put("download.directory_upgrade", true);
    prefs.put("download.default_directory", "path-to-download-directory");
    options.setExperimentalOption("prefs", prefs);
    WebDriver driver = new ChromeDriver(options);

推荐阅读