2

我尝试从 latata.pl/pl.php 获取数据并查看所有符号(波兰语 - iso-8859-2)

 final URL url = new URL("http://latata.pl/pl.php");
    final URLConnection urlConnection = url.openConnection();
    final BufferedReader in = new BufferedReader(new InputStreamReader(
            urlConnection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();

它不起作用。:( 有任何想法吗?

4

5 回答 5

3

InputStream 阅读器有多个构造函数,在这种情况下,您可以(应该/必须)在这些构造函数之一中指定编码。

于 2011-02-27T13:41:34.697 回答
3

InputStreamReader将尝试使用您的平台默认编码(很可能是 UTF-8 或可怕的 Windows 编码之一)转换通过 TCP 连接返回的字节。您应该明确指定编码。

假设 Web 服务器运行良好,您可以在其中一个 HTTP 标头中找到正确的编码(我忘了是哪一个)。或者您可以假设它是 iso-8859-2,但这可能会在以后中断。

于 2011-02-27T13:41:45.697 回答
2

这对于评论来说太长了,但是谁设置了该网页?你?从我可以看到它看起来不正确。

这是您返回的内容:

$ telnet latata.pl 80
Trying 91.205.74.65...
Connected to latata.pl.
Escape character is '^]'.
GET /pl.php HTTP/1.0
Host: latata.pl

HTTP/1.1 200 OK
Date: Sun, 27 Feb 2011 13:49:19 GMT
Server: Apache/2
X-Powered-By: PHP/5.2.16
Vary: Accept-Encoding,User-Agent
Content-Length: 10
Connection: close
Content-Type: text/html

����ʣ��Connection closed by foreign host.

HTML 很简单:

<html>
<head></head>
<body>±ê³ó¿¡Ê£¯¬</body>
</html>

这就是您的页面从浏览器中显示的方式。是否有正当理由在该 HTML 页面中未指定字符集?

于 2011-02-27T13:55:49.927 回答
2

您的 php 脚本的输出pl.php有问题。有一个Content-Type: text/html没有声明字符集的 HTTP 标头集。如果没有声明的字符集,客户端必须假定它ISO-8859-1与 HTTP 规范有关。如果将发送的正文±ê³ó¿¡Ê£¯¬解释为 ISO-8859-1。

php-script 发送的字节表示ąęłóżĄĘŁŻŹ它是否被声明为

Content-Type: text/html; charset=ISO-8859-2

您可以使用简单的代码片段来检查这一点,它将错误的 ISO-8859-1 编码转换为 ISO-8859-2:

final String test="±ê³ó¿¡Ê£¯¬";
String corrupt=new String(test.getBytes("ISO-8859-1"),"ISO-8859-2");
System.out.println(corrupt);    

输出将是ąęłóżĄĘŁŻŹ,这是一些波兰语字符。

作为快速修复,将 php-script 中的字符集设置为输出Content-Type: text/html; charset=ISO-8859-2为 HTTP-Header。

但无论如何,您都应该考虑切换到 UTF-8 编码输出。

于 2011-02-27T15:15:51.667 回答
2

正如有人已经说过的那样,没有为响应指定字符集编码。强制将响应文档视为 ISO-8859-2(通常在中欧使用)会导致显示合法的波兰语字符,因此我假设这是实际使用的编码。由于未指定编码,因此将假定 ISO-8859-1 为默认值。

响应头需要包含头Content-Type: text/html; charset=ISO-8859-2用于正确解释字符代码点。构造响应时将使用此字符集InputStream

于 2011-02-27T15:21:22.413 回答