Volley 请求中的 UTF-8 编码 [英] UTF-8 encoding in Volley Requests
问题描述
在我的 Android 应用程序中,我正在使用 Volley JsonArrayRequest
加载 json 数据.数据是我自己创建的,我用 UTF-8 编码的 Sublime 保存了它们.当我得到 Response
并填写我的 ListView
时,文本显示不正确(变音).这是我的请求的样子:
In my Android app I am loading json data with a Volley JsonArrayRequest
. The data were created by myself and I saved them with Sublime with UTF-8 encoding. When I get the Response
and fill my ListView
, the texts are not displayed correctly (umlauts). This is what my Request looks like:
JsonArrayRequest request = new JsonArrayRequest(targetUrl,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(final JSONArray response) {
try {
fillList(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
当我用这种方法加载完全相同的数据时,所有文本都正确显示:
When I load the exact same data with this method, all texts are displayed correctly:
final StringBuilder builder = new StringBuilder();
final HttpClient client = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet(request);
try {
final HttpResponse response = client.execute(httpGet);
final StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
final HttpEntity entity = response.getEntity();
final InputStream content = entity.getContent();
final BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
所以对我来说,我的 json 文件的编码似乎没有问题.如何在 Volley 中解决此编码问题?
So to me it seems like there is no problem with the encoding of my json file. How can I fix this encoding problem in Volley?
推荐答案
如果您知道您请求的所有文件绝对都是 UTF-8 格式,听起来您就是这样做的,那么您可能会考虑强制您的 Volley 请求返回 UTF-8 格式的字符串.您可以通过对标准 JSON 请求进行子类化来实现这一点.像这样:
If you know that absolutely all of the files you are requesting will be in the UTF-8 format, which it sounds like you do, then you might consider forcing your Volley request to return UTF-8 formatted strings. You could accomplish this by subclassing the standard JSON request. Something like this:
public class Utf8JsonRequest extends JsonRequest<JSONObject> {
...
@Override
protected Response<JSONObject> parseNetworkResponse (NetworkResponse response) {
try {
String utf8String = new String(response.data, "UTF-8");
return Response.success(new JSONObject(utf8String), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
// log error
return Response.error(new ParseError(e));
} catch (JSONException e) {
// log error
return Response.error(new ParseError(e));
}
}
}
这篇关于Volley 请求中的 UTF-8 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!