【问题标题】:Android Volley POST request with header and body带有标头和正文的 Android Volley POST 请求
【发布时间】:2019-01-18 18:22:36
【问题描述】:

我的代码正在尝试将数据发布到服务器,我需要添加一个标头,我正在使用 Volley 库。

如果我不包含“getparams”方法,则请求有效,我可以发布但没有数据。

如果我包含“getparams”方法,请求将失败并返回 400(错误请求)。

我一直无法找出错误在哪里。

         public void tryPost() {
    RequestQueue queue = Volley.newRequestQueue(this);

    String serverUrl = "http://10.0.2.2:3000/tasks";



    StringRequest stringRequest = new StringRequest(Request.Method.POST, serverUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("TAG", "response = "+ response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("TAG", "Error = "+ error);
        }
    })
    {
        //
        @Override
        public Map<String, String> getHeaders()  {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");
            return headers;
        }
        ////
        @Override
        public Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("userId","sargent"); 
            params.put("password","1234567"); 
            return params; //return the parameters
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    }

【问题讨论】:

    标签: android post android-volley


    【解决方案1】:

    对于 Authentication,您应该将该信息包含在 getHeaders 而不是 getParams

    删除 getParams 并将其添加到您的 getHeaders

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
           Map<String, String> headers = new HashMap<>();                
           String credentials = "username:password";
           String auth = "Basic "
                            + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
           headers.put("Accept", "application/json");
           headers.put("Content-Type", "application/json");
           headers.put("Authorization", auth);
           return headers;
    }
    

    希望对你有帮助

    【讨论】:

    • 上面的代码添加了可以正常工作的标头,但是当与参数代码结合使用时,响应是一个错误的请求。
    【解决方案2】:

    我不怎么使用 volley,但我有一个替代方法可以轻松完成你的工作。如果你想使用 AsyncHTTPClient 试试这个。

    public void tryPost(){
       AsynHTTPClient client = new AsyncHTTPClient();
    
       //to add the data which you wanna post 
       RequestParams params = new RequestParams();
       params.add("pass your value","from this value");
       params.put("list","your_list"); // this is for passing the arraylist
    
      client.post(url, params, new AsynchHTTPRespondHandeler(){
      // implement method to get the response from onSuccess()
    
      });
    }
    

    对于 AsynchHTTPClient,请在您的 gradle 中执行此操作:

    compile 'com.loopj.android:android-async-http:1.4.9'
    

    您可以了解有关 RequestParams 的更多信息,以便传递不同的数据here

    我希望你能完成你的工作。如有任何问题,请联系我。

    【讨论】:

    • 如何添加标题?
    • 您是否阅读了有关 RequestParams 的文档,在这里您将知道如何添加这些数据。尝试使用请求参数,这将完成您的工作,或者更精确,以便我弄清楚您实际想要什么,在这里我可以弄清楚您想要添加一些我已经为您解释过的数据。
    • 我阅读了文档,其中没有解释如何添加标题。具体来说,我想做的是 headers.put("Accept", "application/json"); headers.put("Content-Type", "application/json");
    【解决方案3】:

    请查看此链接:

    StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            ///handle response from service
        }, new ErrorResponse() {
          @Override
          public void onErrorResponse(VolleyError volleyError) {
            //handle error response
          }
      }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
              Map<String, String> params = new HashMap<String, String>();
              //add params <key,value>
              return params;
          }
    
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> headers = Constants.getHeaders(context);
            // add headers <key,value>
            String credentials = USERNAME+":"+PASSWORD;
            String auth = "Basic "
                    + Base64.encodeToString(credentials.getBytes(),
                    Base64.NO_WRAP);
            headers.put("Authorization", auth);
            return headers;
          }
      };
     mQueue.add(request);
    

    https://gist.github.com/jchernandez/5bec1913af80e2923da8

    【讨论】:

      【解决方案4】:

      对于 POST 请求,对于 Header 部分,您必须覆盖 getHeaders() 'function',对于您的请求的** payload/body**可以提供 JsonObject 作为“请求”的参数,也可以覆盖 getParams() 'function'

      Kotlin 程序员发帖代码:

      // 创建 Json 有效负载

      val requestJsonPayloadMap = mutableMapOf<String, String>()
              requestJsonPayloadMap["param1"] = "param1Value"
              requestJsonPayloadMap["param2"] = "param2Value"
      
              // Creating JSON Object out of the Hash-map
              val requestJSONObject = JSONObject(requestJsonPayloadMap)
      

      // 将上面的payload传递给下面的请求[那么不需要重写'getParams()'方法]

      val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, requestJSONObject,
                  Response.Listener {
                      // Success Part  
                  },
      
                  Response.ErrorListener {
                      // Failure Part
                  }
              ) {
                  // Providing Request Headers
      
                  override fun getHeaders(): Map<String, String> {
                     // Create HashMap of your Headers as the example provided below
      
                      val headers = HashMap<String, String>()
                      headers["Content-Type"] = "application/json"
                      headers["app_id"] = APP_ID
                      headers["app_key"] = API_KEY
      
                      return headers
                  }
      
                  // Either override the below method or pass the payload as parameter above, dont do both 
      
                  override fun getParams(): Map<String, String> {
                     // Create HashMap of your params as the example provided below
      
                      val headers = HashMap<String, String>()
                      headers["param1"] = "param1Value"
                      headers["param2"] = "param2Value"
                      headers["param3"] = "param3Value"
      
                      return headers
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2021-08-11
        • 2019-12-13
        • 2020-01-02
        • 2017-08-31
        • 2016-09-24
        • 2020-12-23
        • 1970-01-01
        • 2015-11-28
        • 1970-01-01
        相关资源
        最近更新 更多