无法在android中的volley中附加带有post请求的标头

时间:2017-08-31 05:32:33

标签: android json error-handling http-headers android-volley

我正在使用排球库来访问网络服务。在这个库中,我需要附加标题来发布请求,但是我在点击Web服务时遇到错误,即" onErrorResponse:null"

//代码

       JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.e("response", response.toString());
                    pDialog.hide();

                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: " + error.getMessage());
            Toast.makeText(getActivity(), R.string.txt_error_occured, Toast.LENGTH_LONG).show();
            pDialog.hide();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("policyNo", policyNo);
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            params.put("Content-Type", "application/json; charset=utf-8");
            params.put("User-agent", "My useragent");
            return params;
        }

    };

//向请求队列添加请求         AppController.getInstance()。addToRequestQueue(jsonObjReq,tag_json_obj);

3 个答案:

答案 0 :(得分:0)

是否有必要使用截击?你可以改用Retrofit。因为它是最好和最快的网络库之一。

https://futurestud.io/tutorials/retrofit-add-custom-request-header

我在1.5年前使用过这段代码,但是在体内发送j = raw json并且完全正常工作。请检查一次。

    public void updateUserData(final String jsonObject) {
        // Tag used to cancel the request
        showProgressDialog();
        String tag_string_req = "string_req";
        String url = Const.UPDATE_USER_HISTORY;


        final StringRequest strReq = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                hideProgressDialog();
                Log.d(TAG, response.toString());

                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                if (offer) {
                    Intent intent = new Intent(getActivity(), TabsActivity.class);
                    getActivity().startActivity(intent);
                    getActivity().finish();
                } else {
                    fm.popBackStack("quiz2", FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    fm.popBackStack("quiz1", FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    fm.popBackStack("app", FragmentManager.POP_BACK_STACK_INCLUSIVE);
                }
//                transaction.commit();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>();
                header.put("Content-Type", "application/json; charset=utf-8");
                return header;
            }


            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return jsonObject.getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return null;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

答案 1 :(得分:0)

以下是向Volley Post请求添加标题的方法:

final HashMap<String, Object> postParams = new HashMap<String, Object>();
postParams.put("KEY_1", "VAL_1");
postParams.put("KEY_2", "VAL_2");

JsonObjectRequest mRequestEkyc = new JsonObjectRequest(Request.Method.POST,
        "your_url_comes_here", new JSONObject(postParams),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                DisplayUtils.dismissDialog(mContext);
                //parseResponse(response);
            }
        }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        DisplayUtils.dismissDialog(mContext);
        DisplayUtils.displayToast(mContext, error.getMessage());
    }
}) {
    /**
     * Passing request headers
     * */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("KEY_1", "VAL_1");
        return headers;
    }

};


final int timeoutMilliseconds = 300000;
mRequestEkyc.setRetryPolicy(new DefaultRetryPolicy(timeoutMilliseconds, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
ApplicationController.getInstance().addToRequestQueue(mRequestEkyc);

希望这对您有用

答案 2 :(得分:0)

@Throws(AuthFailureError::class)
fun getHeaders(): Map<String, String>? {
    val header: MutableMap<String, String> = HashMap()
    header["Content-Type"] = "application/json; charset=utf-8"
    return header
}

这就是在POST请求Kotlin中添加标头的方法