UTF-8 encoding in Volley Requests

后端 未结 8 1496
天命终不由人
天命终不由人 2020-12-06 02:17

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

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 02:40

    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 {
        ...
        @Override
        protected Response 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));
            }
        }
    }
    

提交回复
热议问题