gpt4 book ai didi

java - 使用HTTP GET下载文件,在java中传递cookie

转载 作者:行者123 更新时间:2023-12-02 03:45:48 26 4
gpt4 key购买 nike

我想用 Java 从 URL 解析 HTML 文档。

当我在浏览器(chrome)中输入网址时,它不会显示 html 页面,但会下载它。

因此,URL 是网页上“下载”按钮后面的链接。到目前为止没有问题。网址为“https://www.shazam.com/myshazam/download-history ”,如果我将其粘贴到浏览器中,则可以正常下载。但是当我尝试使用 java 下载它时,出现 401(禁止)错误。

我在加载 url 时检查了 chrome 网络工具,并注意到我的个人资料数据和注册 cookie 是通过http GET。

我尝试了很多不同的方法,但没有任何效果。所以我的问题是,如何用java生成这个?如何获取(下载)HTML 文件并解析它?

更新:

这是我们迄今为止发现的内容(感谢安德鲁·里根):

BasicCookieStore store = new BasicCookieStore();
store.addCookie( new BasicClientCookie("profile-data", "value") ); // profile-data
store.addCookie( new BasicClientCookie("registration", "value") ); // registration
Executor executor = Executor.newInstance();
String output = executor.use(store)
.execute(Request.Get("https://www.shazam.com/myshazam/download-history"))
.returnContent().asString();

最后一行代码似乎导致了 NullPointerException。其余代码似乎可以正常加载不 protected 网页。

最佳答案

我自己找到了答案。使用 HttpURLConnection,此方法可用于对各种服务进行“身份验证”。我使用 chrome 内置的网络工具来获取 GET 请求的 cookie 值。

HttpURLConnection con = (HttpURLConnection) new URL("https://www.shazam.com/myshazam/download-history").openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("Cookie","registration=Cooki_Value_Here;profile-data=Cookie_Value_Here");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();

关于java - 使用HTTP GET下载文件,在java中传递cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com