gpt4 book ai didi

java - JAVA程序如何结合Http header和read content?

转载 作者:可可西里 更新时间:2023-11-01 17:06:35 27 4
gpt4 key购买 nike

然后我得到了一个应该用来获取 html 内容的程序。

public class University {
public static void main(String[] args) throws Exception {
System.out.println("Started");

URL url = new URL ("http://www.4icu.org/reviews/index2.htm");

URLConnection spoof = url.openConnection();
// Spoof the connection so we look like a web browser
spoof.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");

String connect = url.toString();
Document doc = Jsoup.connect(connect).get();

Elements cells = doc.select("td.i");

Iterator<Element> iterator = cells.iterator();

while (iterator.hasNext()) {
Element cell = iterator.next();
String university = cell.select("a").text();
String country = cell.nextElementSibling().select("img").attr("alt");

System.out.printf("country : %s, university : %s %n", country, university);
}
}
}

但是,似乎有Http header 在阻止访问内容。因此,我创建了以下程序来获取 html 站点的标题。

public class Get_Header {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.4icu.org/reviews/index2.htm");
URLConnection connection = url.openConnection();

Map responseMap = connection.getHeaderFields();
for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(key + " = ");

List values = (List) responseMap.get(key);
for (int i = 0; i < values.size(); i++) {
Object o = values.get(i);
System.out.println(o + ", ");
}
}
}
}

它返回以下结果。

X-Frame-Options = 
SAMEORIGIN,
Transfer-Encoding =
chunked,
null =
HTTP/1.1 403 Forbidden,
CF-RAY =
2ca61c7a769b1980-HKG,
Server =
cloudflare-nginx,
Cache-Control =
max-age=10,
Connection =
keep-alive,
Set-Cookie =
__cfduid=d4f8d740e0ae0dd551be15e031359844d1469853403; expires=Sun, 30-Jul-17 04:36:43 GMT; path=/; domain=.4icu.org; HttpOnly,
Expires =
Sat, 30 Jul 2016 04:36:53 GMT,
Date =
Sat, 30 Jul 2016 04:36:43 GMT,
Content-Type =
text/html; charset=UTF-8,

虽然可以得到header,但是怎么把代码组合成一个完整的呢?

非常感谢 Advnace。

最佳答案

当您再次将其转换回 String 时,您在 URL 上设置的 "User-Agent" 属性似乎丢失了。

在 JSoup 连接上设置用户代理似乎有效:

public static void main(String[] args) throws Exception {
System.out.println("Started");

String url = "http://www.4icu.org/reviews/index2.htm";
Document doc = Jsoup.connect(url).userAgent("Mozilla").get();

Elements cells = doc.select("td.i");

Iterator<Element> iterator = cells.iterator();

while (iterator.hasNext()) {
Element cell = iterator.next();
String university = cell.select("a").text();
String country = cell.nextElementSibling().select("img").attr("alt");

System.out.printf("country : %s, university : %s %n", country, university);
}
}

关于java - JAVA程序如何结合Http header和read content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672161/

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