正文中的 Android Volley POST 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22057023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:28:14  来源:igfitidea点击:

Android Volley POST string in body

androidasp.netrestasp.net-web-apiandroid-volley

提问by Sandak

I'm trying to use Volley library to communicate with my RESTful API.

我正在尝试使用 Volley 库与我的 RESTful API 进行通信。

I have to POST string in the body, when I'm asking for the bearer Token. String should look like this: grant_type=password&username=Alice&password=password123 And header: Content-Type: application/x-www-form-urlencoded

当我要求不记名令牌时,我必须在正文中 POST 字符串。字符串应如下所示:grant_type=password&username=Alice&password=password123 和标题:Content-Type: application/x-www-form-urlencoded

More info about WebApi Individual Accounts: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

有关 WebApi 个人帐户的更多信息:http: //www.asp.net/web-api/overview/security/individual-accounts-in-web-api

Unfortunately I can't figure out how can I solve it..

不幸的是,我不知道如何解决它..

I'm trying something like this:

我正在尝试这样的事情:

StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        VolleyLog.v("Response:%n %s", response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("grant_type", "password");
                        params.put("username", "User0");
                        params.put("password", "Password0");
                        return params;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "application/x-www-form-urlencoded");
                        return headers;
                    }
                };

I'm getting 400 Bad Request all the time. I think that I'm actually sending request like this:

我一直收到 400 个错误的请求。我认为我实际上是在发送这样的请求:

grant_type:password, username:User0, password:Password0

instead of:

代替:

grant_type=password&username=Alice&password=password123

I would be very grateful if anyone has any ideas or an advice..

如果有人有任何想法或建议,我将不胜感激。

采纳答案by Itai Hanski

First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.

首先,我建议您通过打印到日志或使用诸如wireshark 或fiddler 之类的网络嗅探器来准确查看您发送的内容。

How about trying to put the params in the body? If you still want a StringRequestyou'll need to extend it and override the getBody()method (similarly to JsonObjectRequest)

尝试将参数放入体内怎么样?如果您仍然想要 a StringRequest,则需要扩展它并覆盖该getBody()方法(类似于JsonObjectRequest

回答by georgiecasey

To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams()and pass a Map of parameters:

要发送带有用户名和密码等参数的普通 POST 请求(无 JSON),您通常会覆盖getParams()并传递参数映射:

public void HttpPOSTRequestWithParameters() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://www.somewebsite.com/login.asp";
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
        new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                Log.d("Response", response);
            }
        }, 
        new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("ERROR","error => "+error.toString());
            }
        }
            ) {     
        // this is the relevant method
        @Override
        protected Map<String, String> getParams() 
        {  
            Map<String, String>  params = new HashMap<String, String>();
            params.put("grant_type", "password"); 
            // volley will escape this for you 
            params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
            params.put("username", "Alice");  
            params.put("password", "password123");

            return params;
        }
    };
    queue.add(postRequest);
}

And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()

并且要在 Volley StringRequest中将任意字符串作为 POST 正文数据发送,您可以覆盖getBody()

public void HttpPOSTRequestWithArbitaryStringBody() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://www.somewebsite.com/login.asp";
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
        new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                Log.d("Response", response);
            }
        }, 
        new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("ERROR","error => "+error.toString());
            }
        }
            ) {  
         // this is the relevant method   
        @Override
        public byte[] getBody() throws AuthFailureError {
            String httpPostBody="grant_type=password&username=Alice&password=password123";
            // 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();
        }
    };
    queue.add(postRequest);
}

As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.

顺便说一句,Volley 文档不存在,并且 StackOverflow 答案的质量非常糟糕。无法相信像这样的例子的答案已经不存在了。

回答by Ryan Newsom

I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?

我知道这是旧的,但我遇到了同样的问题,在这里找到了一个更清晰的解决方案:How to send a POST request using volley with string body?