提供重定向的URL是一个带空格的URL,Jsoup会导致错误。怎么解决这个?

时间:2013-08-17 20:14:35

标签: java redirect uri jsoup

您好我必须解析通过服务器重定向解析URI的页面。

示例:

我重定向的http://www.juventus.com/wps/poc?uri=wcm:oid:91da6dbb-4089-49c0-a1df-3a56671b7020http://www.juventus.com/wps/wcm/connect/JUVECOM-IT/news/primavera%20convocati%20villar%20news%2010agosto2013?pragma=no-cache

这是我必须解析的页面的URI。问题是重定向URI包含空格,这是代码。

    String url = "http://www.juventus.com/wps/poc?uri=wcm:oid:91da6dbb-4089-49c0-a1df-3a56671b7020";
    Document doc = Jsoup.connect(url).get();

    Element img = doc.select(".juveShareImage").first();
    String imgurl = img.absUrl("src");
    System.out.println(imgurl);

我在第二行收到此错误:

    Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=http://www.juventus.com/wps/wcm/connect/JUVECOM-IT/news/primavera convocati villar news 10agosto2013?pragma=no-cache

包含重定向的url,因此这意味着JSoup获取了正确的重定向URI。有没有办法用%20替换'',所以我可以解析没问题?

谢谢!

2 个答案:

答案 0 :(得分:2)

你是对的。这就是问题。我看到的唯一解决方案是执行重定向手册。我写了这个小的递归方法为你做这个。参见:

public static void main(String[] args) throws IOException
{
    String url = "http://www.juventus.com/wps/poc?uri=wcm:oid:91da6dbb-4089-49c0-a1df-3a56671b7020";

    Document document = manualRedirectHandler(url);

    Elements elements = document.getElementsByClass("juveShareImage");

    for (Element element : elements)
    {
        System.out.println(element.attr("src"));
    }

}

private static Document manualRedirectHandler(String url) throws IOException
{
    Response response = Jsoup.connect(url.replaceAll(" ", "%20")).followRedirects(false).execute();
    int status = response.statusCode();

    if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
    {
        String redirectUrl = response.header("location");
        System.out.println("Redirect to: " + redirectUrl);
        return manuelRedirectHandler(redirectUrl);
    }

    return Jsoup.parse(response.body());
}

这会打印出来

Redirect to: http://www.juventus.com:80/wps/portal/!ut/p/b0/DcdJDoAgEATAF00GXFC8-QqVWwMuJLLEGP2-1q3Y8Mwm4Qk77pATzv_L6-KQgx-09FDeWmpEr6nRThCk36hGq1QnbScqwRMbNuXCHsFLyuTgjpVLjOMHyfCBUg!!/
Redirect to: http://www.juventus.com/wps/wcm/connect/JUVECOM-IT/news/primavera convocati villar news 10agosto2013?pragma=no-cache
/resources/images/news/inlined/42d386ef-1443-488d-8f3e-583b1e5eef61.jpg

我还为Jsoup添加了一个补丁:

答案 1 :(得分:1)

尝试相反

String url = "http://www.juventus.com/wps/wcm/connect/JUVECOM-IT/news/primavera%20convocati%20villar%20news%2010agosto2013";
        Document doc = Jsoup.connect(url)
        .data("pragma", "no-cache")
        .get();

        Element img = doc.select(".juveShareImage").first();

        String imgurl = img.absUrl("src");
        System.out.println(imgurl);