Fail with UTF-8 encoding in Volley Requests

2019-04-12 16:07发布

问题:

I made a project(BlogReader) using Volley library. If I encode json file in UTF-8 and reload my AndroidStudio Emulator the list view become white(white blank with menu header) . If I change json encode again on ANSI or win-1251 It starts to works. I changed Android File Encoding Settings on UTF-8, but nothing changed. How fix this problem?

PS. Sorry, can't load screenshot, very low reputation(

回答1:

To display the strings in UTF8 encoding Cyrillic, it helped me a lot:

newStr = URLDecoder.decode(URLEncoder.encode(oldStr, "iso8859-1"),"UTF-8");


回答2:

Assuming that this is an http request then the first way is to encode the server's response with UTF-8. The implementation depends on the type of server.

But if you want to enforce UTF-8 encoding in all responses then you need to override a request parseNetworkResponse. For example this code below is for StringRequest:

public class UTF8StringRequest extends StringRequest {
  public UTF8StringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
    super(method, url, listener, errorListener);
  }

  public UTF8StringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
    super(url, listener, errorListener);
  }

  @Override
  protected Response<String> parseNetworkResponse(NetworkResponse response) {

    String utf8String = null;
    try {
        utf8String = new String(response.data, "UTF-8");
        return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));

    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    }
  }
}