Volleyball POST request, error 400

This is the first time I'm working with JSON, but I'm experimenting with POST requests.

I want to make a POST request to this site http://jsonblob.com/api

My code works when I use asynctask + httppost

private static final String url = "http://jsonblob.com/api/jsonBlob";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new PostJsonTask().execute();
}

private class PostJsonTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            HttpResponse response = post();
            Header s = response.getFirstHeader("Location");
            Log.d("PostJsonTask", s.getValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private HttpResponse post() throws Exception {
        // convert parameters into JSON object
        Map<String, String> params = new HashMap<String, String>();
        params.put("user", "Robby");
        params.put("pass", "zqdqzdqdqzd");
        JSONObject holder = new JSONObject(params);

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity se = new StringEntity(holder.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");
        post.setEntity(se);
        return client.execute(post);
    }
}

With this code, I can successfully get the Location parameter.

But I want to do this using the Volley library, I already have the following code:

private static final String url = "http://jsonblob.com/api/jsonBlob";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");
            headers.put("Content-type", "application/json");

            return headers;
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("user", "Robby");
            params.put("pass", "zqdqzdqdqzd");

            return params;
        }

        @Override
        protected Response<String> parseNetworkResponse(
                NetworkResponse response) {
            Map<String, String> headers = response.headers;
            String location = headers.get("Location");
            Log.d("PostJsonTask", location);

            return super.parseNetworkResponse(response);
        }
    };

    queue.add(request);
}

private ErrorListener createErrorListener() {
    return new ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    };
}

private Listener<String> createResponseListener() {
    return new Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d("PostJsonTask", response);
        }
    };
}

But this returns a VolleyError with code 400. How can I fix this?

+4
source share
2 answers

instead of trying to set the Content-type of the header, try setting for bodyContentType and in postman (web) also you set the content type of the body only

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                        url, obj,
                        new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                Log.d("Response", response.toString());

                            }
                        }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.d("Error", error.toString());
                                }
                        })

                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }
                };
+2

getParams.

JSON , JsonObjectRequest ( JsonObjectRequest StringRequest),

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("user", "Robby");
    jsonObject.put("pass", "zqdqzdqdqzd");
} catch (JSONException e) {
    // handle exception (not supposed to happen)
}

StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {

    // your code without getParams

    @Override
    public byte[] getBody() {
        try {
            return jsonObject.toString.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            // not supposed to happen
            return null;
        }
    }
}
+1

Source: https://habr.com/ru/post/1541098/


All Articles