【发布时间】:2012-11-18 11:22:11
【问题描述】:
我目前正在开发一个具有大量服务器端通信的 Android 应用程序。昨天我收到一个错误报告,说用户无法发送(简单)特殊字符,例如 ëäï。
我搜索了但没有找到任何有用的信息 可能重复(没有答案): https://stackoverflow.com/questions/12388974/android-httpurlconnection-post-special-charactes-to-rest-clint-in-android
我的相关代码:
public void execute(String method) {
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(this.url);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setReadTimeout(30 * 1000);
urlConnection.setDoInput(true);
if (secure)
urlConnection.setRequestProperty("Authorization", "Basic " + getCredentials());
if (body != null) {
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setFixedLengthStreamingMode(body.length());
urlConnection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(body);
dos.flush();
dos.close();
}
responseCode = urlConnection.getResponseCode();
message = urlConnection.getResponseMessage();
InputStream in = null;
try {
in = new BufferedInputStream(urlConnection.getInputStream(), 2048);
} catch (Exception e) {
in = new BufferedInputStream(urlConnection.getErrorStream(), 2048);
}
if (in != null)
response = convertStreamToString(in);
} catch (UnknownHostException no_con) {
responseCode = 101;
}catch (ConnectException no_con_2){
responseCode = 101;
}catch(IOException io_ex){
if(io_ex.getMessage().contains("No authentication challenges found")){
responseCode = 401;
}else
responseCode = 101;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
body 是一个字符串 ;-)
希望我们能一起解决这个问题
更新:
试过了:
writeUTF()
需要一个能够理解修改后的 UTF-8 的服务器
byte[] buf = body.getBytes("UTF-8");
dos.write(buf, 0, buf.length);
字符串有效,但没有特殊字符
更新:得到它使用 StringEntity(* string, "UTF-8") 然后将结果解析为 byte[] 并使用 dos.write(byte[]) 写入它!
--
【问题讨论】:
-
阅读 writeBytes 文档。请改用 writeUTF。
-
听起来确实很公平。我如何获得该字符串的长度。我现在在指定错误长度时遇到错误
-
这是有道理的,因为有些字符是在几个字节上编码的。您可以尝试不指定长度,您可以使用 writeChars(但效率较低,因为所有字符都是 2 字节),您可以使用 String.getBytes("UTF-8").length(但这会创建一个相当长无用的字节[])。另外,请注意 DataOutputStream.writeUTF 是一种自定义格式,它在开头添加字符串的长度,旨在由 DataInputStream 读取。 (但这取决于您的服务器)
-
是的,我没有指定长度就让它工作了。但是服务器不是Java,不识别writeUTF修改的UTF编码。还有其他想法吗?
-
也试过 byte[] buf = body.getBytes("UTF-8"); dos.write(buf, 0, buf.length);但是特殊字符仍然不起作用