java - 通过身份验证将 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 做一些事情,即:获取文本。
解决方案
为避免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);
推荐阅读
- javascript - 如何在循环中使用函数或调用函数
- php - 如何修复 array_count_value 中的空白错误
- parsing - 如何在Lua中解析一系列带有空格的字符串
- excel-formula - 多列 VLOOKUP
- c# - 还有另一种方法可以将 ffmpeg 中的帧导出到 texture2d 吗?我的代码在 Windows 上工作,但在 Linux 上不工作
- csv - 在 AHK 中,如何正确使用 StrSplit 从 CSV 文件中创建一个数组,然后在特定条件下对其进行解析?
- python - 如何使用 Python/Regex 用变量替换/替换部分 url
- typescript - 为什么没有 @types 用于 Semantic-ui-react?@types/semantic-ui 会起作用吗?我可以不用@types 吗?
- javascript - 即使使用全局变量,也存在从 jquery click 函数外部访问变量的问题
- r - kknn分类:如何确定kmax的值?