android-VolleyPlus:NetworkDispatcher.run:未处理的异常java.lang.NullPointerException

我正在尝试运行以下代码:

Map<String, Object> requestMap = new HashMap<>();
Long unixTime = System.currentTimeMillis() / LONG_1000;
requestMap.put(KEY_TIME, unixTime);
JWTSigner signer = new JWTSigner(SECRET);
String token = signer.sign(requestMap);
String url = BASE_URI + "/Data/Categories?d=" + token;
StringRequest stringRequest =  new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d(TAG, response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, error.getLocalizedMessage());
    }
});

RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
mRequestQueue.add(stringRequest);

但是我收到以下错误:

[6056] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference
    at com.android.volley.toolbox.HttpHeaderParser.parseCharset(HttpHeaderParser.java:243)
    at com.android.volley.toolbox.HttpHeaderParser.parseCharset(HttpHeaderParser.java:262)
    at com.android.volley.request.StringRequest.parseNetworkResponse(StringRequest.java:70)
    at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:133)
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference

我不知道问题出在哪里.有人可以帮忙吗?

提前致谢.

最佳答案
您需要在StringRequest中重写parseNetworkResponse方法,并修复一个不会出现空标题映射的漏洞:

StringRequest stringRequest =  new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d(TAG, response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, error.getLocalizedMessage());
    }
}) {
    @Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
        if (response.headers == null)
        {
            // cant just set a new empty map because the member is final.
            response = new NetworkResponse(
                               response.statusCode,
                               response.data,
                               Collections.<String, String>emptyMap(), // this is the important line, set an empty but non-null map.
                               response.notModified,
                               response.networkTimeMs);


        }

        return super.parseNetworkResponse(response);
    }
};

希望这可以帮助.

转载注明原文:android-VolleyPlus:NetworkDispatcher.run:未处理的异常java.lang.NullPointerException - 代码日志