【问题标题】:Jsoup connect doesn't work correctly when link has Turkish letters当链接有土耳其字母时,Jsoup 连接无法正常工作
【发布时间】:2014-01-15 19:55:04
【问题描述】:

我正在使用Jsoup 从网站获取 html。我正在使用

String url="http://www.example.com";
Document doc=Jsoup.connect(url).get();

此代码获取 html。但是当我在这样的链接中使用一些土耳其语字母时;

String url="http://www.example.com/?q=Türkçe";
Document doc=Jsoup.connect(url).get();

Jsoup 像这样发送请求:"http://www.example.com/?q=Trke"

所以我无法得到正确的结果。我该如何解决这个问题?

【问题讨论】:

    标签: java jsoup turkish


    【解决方案1】:

    工作解决方案,如果编码是UTF-8,那么只需使用

    Document document = Jsoup.connect("http://www.example.com")
            .data("q", "Türkçe")
            .get();
    

    结果

    URL=http://www.example.com?q=T%C3%BCrk%C3%A7e
    

    对于自定义编码,可以使用:

    String encodedUrl = URLEncoder.encode("http://www.example.com/q=Türk&#231e", "ISO-8859-3");
    String encodedBaseUrl = URLEncoder.encode("http://www.example.com/q=", "ISO-8859-3");
    String query = encodedUrl.replace(encodedBaseUrl, "");
    
    Document doc= Jsoup.connect("http://www.example.com")
            .data("q", query)
            .get();
    

    【讨论】:

    • @ErdinçÖzdemir 抱歉,我的帖子搞砸了,哪个有效:)
    • 编码为 UTF-8。第二个才是真正的答案。
    【解决方案2】:

    根据the specification,URL 中不允许使用Unicode 字符。我们习惯于看到它们,因为浏览器会在地址栏中显示它们,但它们不会发送到服务器。

    在将路径传递给JSoup 之前,您必须对路径进行 URL 编码。 MariuszS 提出的Jsoup.connect("http://www.example.com").data("q", "Türkçe") 就是这样做的

    【讨论】:

      【解决方案3】:

      我在谷歌上找到了这个:http://turkishbasics.com/resources/turkish-characters-html-codes.php 也许你可以像这样添加它:

       String url="http://www.example.com/?q=Türk&#231e";
       Document doc=Jsoup.connect(url).get();
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-11
      • 2012-12-27
      • 2013-11-04
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多