java - WGET 和 HttpClient 可以工作,但 Jsoup 在 java 中不起作用

标签 java jsoup httpclient wget

我正在尝试使用 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() 方法的参数才能使其工作吗?

但是,并非所有网址都会发生这种情况。这种情况特别发生在该网站的页面上:

http://xyo.net/iphone-app/instagram-RrkBUFE/

最佳答案

您需要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/

相关文章:

Java套接字: Get clients external IP

java - 如何在java GUI中锁定内部框架

java - AIX - 无法创建 VM 线程。系统资源不足

java - 将字符串日期转换为新格式 Java

java - 无法创建新的 PoolingHttpClientConnectionManager

java - Solr - 使用 Httpclient 实例化 HttpSolrServer

C#:HttpClient,将多个文件作为 MultipartFormDataContent 上传时的文件上传进度

java - Android 版 Jsoup 帮助 - 如何从表格中获取元素中的文本?

java - Jsoup:获取某个元素之前的所有元素/删除某个元素之后的所有元素

java - 如何从ajax网页获取所有文本内容