Fail with UTF-8 encoding in Volley Requests

若如初见. 提交于 2020-01-01 18:17:17

问题


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));
    }
  }
}


来源:https://stackoverflow.com/questions/30472366/fail-with-utf-8-encoding-in-volley-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!