问题描述
||
我现在开发一个德语应用程序,它将JSON中的数据提取到ListView中。由于有一些特殊字符,例如üöäß,下面有我的代码,因此这些字符显示为?。
有人可以帮助我解决我的问题吗?谢谢
public class LooserSync extends IntentService {
public LooserSync() {
super(\"LooserSyncService\");
}
@Override
protected void onHandleIntent(Intent intent) {
Database.OpenHelper dbhelper = new Database.OpenHelper(getBaseContext());
SQLiteDatabase db = dbhelper.getWritableDatabase();
DefaultHttpClient httpClient = new DefaultHttpClient();
db.beginTransaction();
HttpGet request = new HttpGet(
\"http://liebenwald.spendino.net/admanager/dev/android/projects.json\");
try {
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream instream = response.getEntity().getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(
instream),8000);
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
instream.close();
String bufstring = total.toString();
JSONArray arr = new JSONArray(bufstring);
Database.Tables tab = Database.Tables.AllTables.get(Database.Project.NAME);
tab.DeleteAll(db);
for (int i = 0; i < arr.length(); i++) {
tab.InsertJSON(db,(JSONObject) arr.get(i));
}
db.setTransactionSuccessful();
}
} catch (Exception e) {
e.printStackTrace();
}
db.endTransaction();
db.close();
}
}
解决方法
JSON内容使用UTF-8作为默认字符集(请参阅RFC 4627,第3章)。您必须确保服务器以正确的编码返回响应,并且为流读取器显式使用UTF-8编码:
BufferedReader r = new BufferedReader(new InputStreamReader(instream,\"UTF-8\"),8000);
,尝试显式定义InputStreamReader的编码,例如:
String encoding = \"ISO-8859-1\";
BufferedReader reader = new BufferedReader(new InputStreamReader(is,encoding));
,使用以下代码获取德语数据,因为该数据采用UTF-8标准
HttpGet request = new HttpGet(
\"http://liebenwald.spendino.net/admanager/dev/android/projects.json\");
httpget.setHeader(\"charset\",\"utf-8\");
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws HttpResponseException,IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
return entity == null ? null : EntityUtils.toString(entity,\"UTF-8\");
}
}
String html = httpclient.execute(request,responseHandler);
谢谢
迪帕克
,可能的重复:Android Java UTF-8 HttpClient问题。
通常,如果您期望的不是ASCII字符,则需要考虑编码。服务器告诉您的是编码,以及如何正确解码。
,这是您的URL返回的响应标头:
Accept-Ranges:none
Connection:Keep-Alive
Content-Length:14572
Content-Type:text/plain
Date:Thu,26 May 2011 11:47:52 GMT
ETag:\"404f6-38ec-4a42a184b1c80;4a0b4ae611cc0\"
Keep-Alive:timeout=15,max=100
Last-Modified:Thu,26 May 2011 09:03:30 GMT
Server:Apache
Content-Type
标头缺少字符集语句。如果您可以更改它,那么它应该起作用。
编辑:如果无法更改,则需要将字符集硬编码为InputStreamReader
的第二个参数。