【问题标题】:Add Payload to Volley post request将有效负载添加到 Volley 发布请求
【发布时间】:2016-05-01 23:05:55
【问题描述】:

我使用 Volley 作为我的 http 客户端库。 我需要将有效载荷原始数据作为 Volley 请求的一部分发送吗? 有这样的帖子:How to send Request payload to REST API in java?

但是如何使用 Volley 来实现呢?

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    需要使用 StringRequest 作为 djodjo 提到的。 还需要覆盖 getBody 方法 - 取自这里 Android Volley POST string in body

    @Override
                    public byte[] getBody() throws AuthFailureError {
                        String httpPostBody="your body as string";
                        // usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
                        try {
                            httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+ URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
                        } catch (UnsupportedEncodingException exception) {
                            Log.e("ERROR", "exception", exception);
                            // return null and don't pass any POST string if you encounter encoding error
                            return null;
                        }
                        return httpPostBody.getBytes();
                    }
    

    【讨论】:

    • 你不需要这样做。 Volley可以处理这些。请检查我的更新答案。
    【解决方案2】:

    示例:

        final TextView mTextView = (TextView) findViewById(R.id.text);
    ...
    
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";
    
    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Display the first 500 characters of the response string.
            mTextView.setText("Response is: "+ response.substring(0,500));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    

    查看the source and more info here

    **更新:**如果您需要添加参数,您可以简单地覆盖getParams()

    例子:

      @Override
    protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
          params.put("param1", "val1");
          params.put("randomFieldFilledWithAwkwardCharacters","{{%stuffToBe Escaped/"); 
          return params;
        }
    

    您不需要自己覆盖getBody,也不需要编码特殊字符,因为 Volley 正在为您执行此操作。

    【讨论】:

    • 确实是字符串请求。您还需要覆盖 public byte[] getBody()
    • 你不知道。你没有具体说明你想要什么。检查更新。
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2018-10-14
    • 1970-01-01
    • 2017-02-22
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多