Java UTF-8 编码未设置为 URLConnection

标签 java unicode utf8-decode

我正在尝试从 http://api.freebase.com/api/trans/raw/m/0h47 检索数据

正如您在文本中看到的那样,有这样的歌曲:/ælˈdʒɪəriə/

当我尝试从页面获取源代码时,我得到的文本包含 ú 等内容。

到目前为止,我已尝试使用以下代码:

urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

我做错了什么?

我的整个代码:

URL url = null;
URLConnection urlConn = null;
DataInputStream input = null;
try {
url = new URL("http://api.freebase.com/api/trans/raw/m/0h47");
} catch (MalformedURLException e) {e.printStackTrace();}

try {
    urlConn = url.openConnection(); 
} catch (IOException e) { e.printStackTrace(); }
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

urlConn.setDoInput(true);
urlConn.setUseCaches(false);

StringBuffer strBseznam = new StringBuffer();
if (strBseznam.length() > 0)
    strBseznam.deleteCharAt(strBseznam.length() - 1);

try {
    input = new DataInputStream(urlConn.getInputStream()); 
} catch (IOException e) { e.printStackTrace(); }
String str = "";
StringBuffer strB = new StringBuffer();
strB.setLength(0);
try {
    while (null != ((str = input.readLine()))) 
    {
        strB.append(str); 
    }
    input.close();
} catch (IOException e) { e.printStackTrace(); }

最佳答案

HTML 页面是 UTF-8,可以使用阿拉伯字符等。但是那些高于 Unicode 127 的字符仍然被编码为数字实体,如 ú。 Accept-Encoding 不会有帮助,因为 UTF-8 是完全正确的加载。

您必须自己解码实体。像这样的东西:

String decodeNumericEntities(String s) {
    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile("\\&#(\\d+);").matcher(s);
    while (m.find()) {
        int uc = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, "");
        sb.appendCodepoint(uc);
    }
    m.appendTail(sb);
    return sb.toString();
}

顺便说一下,这些实体可能源自经过处理的 HTML 表单,因此在 Web 应用程序的编辑端。


在有问题的代码之后:

我已将 DataInputStream 替换为文本的 (Buffered)Reader。 InputStreams读取二进制数据,字节;读者文本,字​​符串。 InputStreamReader 具有一个 InputStream 和一个编码作为参数,并返回一个 Reader。

try {
    BufferedReader input = new BufferedReader(
            new InputStreamReader(urlConn.getInputStream(), "UTF-8")); 
    StringBuilder strB = new StringBuilder();
    String str;
    while (null != (str = input.readLine())) {
        strB.append(str).append("\r\n"); 
    }
    input.close();
} catch (IOException e) {
    e.printStackTrace();
}

关于Java UTF-8 编码未设置为 URLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934797/

相关文章:

python - 在 Windows 中将希伯来语文件名作为命令行参数传递

java - 维吉尼亚密码 java UTF-8

java - 如何读取服务器java.nio中的字符集UTF-8编码缓冲区

windows - 在 python 2.7 ctypes 中构建 UCS4 字符串缓冲区

php - 如何用 PHP 将 UTF-8 字符替换为外观相似的 ASCII 字符?

java - 我如何需要在下拉菜单中正确选择项目?

java - main方法线程将在哪里创建

java - 如何使用另一个方法中定义的数组变量?

java - Spring 2.1.0.M4rabbitmq声明队列并在运行时将它们绑定(bind)到监听器

Python 2.7、Appengine 数据存储和 Unicode