我正在尝试使用 Jsoup 通过 java 代码获取网页的 html 源代码。下面是我用来获取页面的代码。我收到 500 内部服务器错误。
String encodedUrl = URIUtil.encodePathQuery(urlToFetch.trim(), "ISO-8859-1");
Response res = Jsoup.connect(encodedUrl)
.header("Accept-Language", "en")
.userAgent(userAgent)
.data(data)
.maxBodySize(bodySize)
.ignoreHttpErrors(true)
.ignoreContentType(true)
.timeout(10000)
.execute();
但是,当我从命令行使用 wget 获取同一页面时,它可以工作。来自代码的简单 HttpClient 也可以工作。
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
我需要更改 Jsoup.connect() 方法的参数才能使其工作吗?
但是,并非所有网址都会发生这种情况。这种情况特别发生在该网站的页面上:
最佳答案
您需要Accept
header 。
试试这个:
String encodedUrl = "http://xyo.net/iphone-app/instagram-RrkBUFE/";
Response res = Jsoup.connect(encodedUrl)
.header("Accept-Language", "en")
.ignoreHttpErrors(true)
.ignoreContentType(true)
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.followRedirects(true)
.timeout(10000)
.method(Connection.Method.GET)
.execute();
System.out.println(res.parse());
它有效。
另请注意,该网站正在尝试设置 cookie,您可能需要处理它们。
希望能有所帮助。
关于java - WGET 和 HttpClient 可以工作,但 Jsoup 在 java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552808/