【问题标题】:Not able to attach header with post request in volley in android无法在 android 的 volley 中附加带有 post 请求的标头
【发布时间】:2018-02-08 23:06:10
【问题描述】:

我正在使用 volley 库访问 Web 服务。在这个库中,我需要附加标头来发布请求,但是在访问 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);

【问题讨论】:

  • 你怎么知道错误是因为标题?
  • 试试这种方式:使用StringRequest 代替JsonObjectRequest 并且不要在参数中添加Content-Type,只传递需要值的参数。有时响应以json字符串形式出现,新手认为必须使用JSON但它应该需要正常的StringRequest。

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


【解决方案1】:
@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 中添加 header 的方法

【讨论】:

    【解决方案2】:

    以下是向 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);
    

    希望这对你有用

    【讨论】:

      【解决方案3】:

      有必要使用凌空吗?您可以改用 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);
          }
      

      【讨论】:

      • 您的回答显示StringRequest,而操作员要求JSONObjectRequest
      • 这不是问题,您可以稍后将其转换为 jsonobject。 JsonObject responseObject= new JsonObject(stringResponse);
      猜你喜欢
      • 2017-08-31
      • 1970-01-01
      • 2021-08-11
      • 2019-12-13
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2016-09-24
      相关资源
      最近更新 更多