Send raw post request using volley

2020-06-17 06:41发布

问题:

I want to send post request with raw string rather than setting params using volley.

I have tried to override the getBody method in StringRequest like following:

@Override
public byte[] getBody() throws AuthFailureError {
    return rawString.getBytes();
}

It won't even send the request and gives the error: com.android.volley.TimeoutError

Any help will be appreciated.

回答1:

I got so ...

   RequestQueue queue = Volley.newRequestQueue(this);

    queue.add(myReq);

    ...

        StringRequest myReq = new StringRequest(Request.Method.POST,
                        server+"Login",
                        createMyReqSuccessListener(),
                        createMyReqErrorListener()) {

                    @Override
                    public byte[] getBody() throws com.android.volley.AuthFailureError {
                        String str = "{\"login\":\""+login+"\",\"password\":\""+pass+"\"}";
                        return str.getBytes();
                    };

                    public String getBodyContentType()
                    {
                        return "application/json; charset=utf-8";
                    }

                };

        ...

            private Response.Listener<String> createMyReqSuccessListener() {
                return new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i(TAG,"Ski data from server - "+response);
                    }
                };
            }


            private Response.ErrorListener createMyReqErrorListener() {
                return new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i(TAG,"Ski error connect - "+error);
                    }
                };
            }