带有重音字符的 URLConnection 编码问题 [英] URLConnection encoding issue with accent character

查看:30
本文介绍了带有重音字符的 URLConnection 编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试发送文本时遇到了 URLConnection 编码问题.

I've got an issue with the URLConnection encoding trying to send a text.

我的代码是这样的:

final URL url = new URL(urlString);
final URLConnection urlConnection = url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");

final DataOutputStream urlDataOut = new DataOutputStream(urlConnection.getOutputStream());
urlDataOut.writeBytes(prepareData.toString());
urlDataOut.flush();
urlDataOut.close();

我的 prepareData.toString() 包含一个带有è"的单词,一旦写入 urlDataOut,它将包含带有问号而不是è"字母的菱形和写入状态为 FAILURE.

My prepareData.toString() contains a word with an "è" and as soon as the urlDataOut is written it will contain the diamond with the question mark instead of the "è" letter and the status of the write is FAILURE.

有人知道如何面对这个问题吗?

Does anybody know how to face this issue?

推荐答案

DataOutputStream.writeBytes 方法不适用于任何字符编码.它的文档说:

The method DataOutputStream.writeBytes method is not suitable for any character encoding. Its documentation says:

通过丢弃其高八位,按顺序写出字符串中的每个字符.

Each character in the string is written out, in sequence, by discarding its high eight bits.

使用writeUTF 方法也不可行.它写入两个字节,其中包含编码的 String 的长度(字节数),服务器会在开头将其解释为字符.

Using the method writeUTF will not be feasible either. It writes two bytes containing the length of the encoded String (number of bytes) which the server would interpret as characters at the beginning.

因此您应该使用标准方式将文本写入OutputStream:

So you should use the standard way of writing text to an OutputStream:

Writer w=new OutputStreamWriter(
                  urlConnection.getOutputStream(), StandardCharsets.UTF_8);
w.write(prepareData.toString());
w.flush();
w.close();

这篇关于带有重音字符的 URLConnection 编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆