当链接具有土耳其语字母时,Jsoup连接无法正常工作

时间:2014-01-15 08:44:08

标签: java jsoup turkish

我正在使用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"

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

3 个答案:

答案 0 :(得分:5)

工作解决方案,如果编码为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();

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

我在google上找到了这个: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();