Android Volley POST字符串在体内

时间:2014-02-27 01:10:30

标签: android asp.net rest asp.net-web-api android-volley

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

当我要求持有者令牌时,我必须在正文中发布字符串。字符串应如下所示: grant_type =密码&安培;用户名=爱丽丝&安培;密码= password123 标题: 内容类型:application / x-www-form-urlencoded

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

不幸的是我无法弄清楚如何解决它..

我正在尝试这样的事情:

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;
                    }
                };

我一直收到400 Bad Request。 我想我实际上是在发送这样的请求:

grant_type:password, username:User0, password:Password0

而不是:

grant_type=password&username=Alice&password=password123

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

3 个答案:

答案 0 :(得分:27)

要发送包含用户名和密码等参数的普通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);
}

要在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);
}

另外,Volley文档不存在,StackOverflow答案的质量非常糟糕。不能相信像这样的例子的答案已经不存在了。

答案 1 :(得分:7)

首先,我建议您通过打印到日志或使用wirehark或fiddler等网络嗅探器来确切了解您要发送的内容。

试图将护身符放入体内怎么样?如果您仍然需要StringRequest,则需要对其进行扩展并覆盖getBody()方法(类似于JsonObjectRequest

答案 2 :(得分:3)

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