12

How to pass these parameter into POST method using Volley library.

API link: http://api.wego.com/flights/api/k/2/searches?api_key=12345&ts_code=123
Screenshot of JSON structure

I tried this but again facing error.

StringEntity params= new StringEntity ("{\"trip\":\"[\"{\"departure_code\":\","
                     +departure,"arrival_code\":\"+"+arrival+","+"outbound_date\":\","
                     +outbound,"inbound_date\":\","+inbound+"}\"]\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");

Please visit here for the details of API.

Nipun
  • 990
  • 1
  • 16
  • 25
Pawandeep
  • 315
  • 1
  • 3
  • 19
  • quick tip: switch to Okhttp or retrofit, volley is slower and would be hard from a beginner's perspective, while okhttp would be easier for you! – OBX Oct 17 '16 at 05:48
  • What you need to do is to pass the json as body in the post request using okhttp, let me know if this helps you : http://stackoverflow.com/questions/34179922/okhttp-post-body-as-json – OBX Oct 17 '16 at 05:59
  • If you insist on using Volley itself, you can refer this question too: http://stackoverflow.com/questions/23220695/send-post-request-with-json-data-using-volley – OBX Oct 17 '16 at 06:03
  • @superman thanks . I'll try – Pawandeep Oct 17 '16 at 06:07
  • Solved the problem? – OBX Oct 17 '16 at 06:53
  • @superman no :( – Pawandeep Oct 17 '16 at 07:09
  • try { HttpPost request = new HttpPost("http://api.wego.com/flights/api/k/2/searches?api_key=123&ts_code=123"); StringEntity params =new StringEntity("{\"trip\":\"[\"{\"departure_code\":\",",departure,"arrival_code\":\",",arrival,"outbound_date\":\",",outbound,"inbound_date\":\",",inbound,"}\"""]"); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); } – Pawandeep Oct 17 '16 at 07:11
  • what's your email? – OBX Oct 17 '16 at 07:13
  • email-id monikaarora1990@gmail.com – Pawandeep Oct 17 '16 at 07:15

3 Answers3

35

Usual way is to use a HashMap with Key-value pair as request parameters with Volley

Similar to the below example, you need to customize for your specific requirement.

Option 1:

final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");

JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   //Process os success response
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);

NOTE: A HashMap can have custom objects as value

Option 2:

Directly using JSON in request body

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("firstkey", "firstvalue");
    jsonBody.put("secondkey", "secondobject");
    final String mRequestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("LOG_VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("LOG_VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {

                responseString = String.valueOf(response.statusCode);

            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}
Sreehari
  • 5,621
  • 2
  • 25
  • 59
  • i just post these parameter in post method – Pawandeep Oct 17 '16 at 06:41
  • { "trips": [ { "departure_code": "SYD", "arrival_code": "LON", "outbound_date": "2014-01-24", "inbound_date": "2014-01-29" } ], "adults_count": 1, "locale": "ar" } – Pawandeep Oct 17 '16 at 06:41
  • @ Stallion yes i pass these parameter in post method ...check link its flight api – Pawandeep Oct 17 '16 at 07:08
  • @ Stallion ur code work for me but little bit issue facing please help me – Pawandeep Oct 17 '16 at 10:20
  • What's the issue you are facing ? I guess if its the problem with JSON forming , then this solution will help. http://stackoverflow.com/questions/37894424/how-to-generate-json-stringer-in-android-for-this-format/37894478#37894478 – Sreehari Oct 17 '16 at 12:31
  • @ Stallion yes output :{"adults_count":"1","inbound_date":"2014-01-29","arrival_code":"LON","departure_code":"SYD","outbound_date":"2014-01-24"} but i want this output :- { "trips": [ { "departure_code": "SYD", "arrival_code": "LON", "outbound_date": "2014-01-24", "inbound_date": "2014-01-29" } ], "adults_count": 1 } – Pawandeep Oct 17 '16 at 12:36
  • @ Stallion Thanks alot Today you saved my life :) thank you so much – Pawandeep Oct 17 '16 at 12:59
  • i got response status 200 not full response ..u can help me ? – Pawandeep Oct 18 '16 at 05:17
  • What do you mean by not full response ? – Sreehari Oct 18 '16 at 07:14
  • thanks for reply .. now i got full response in json format – Pawandeep Oct 18 '16 at 12:37
  • but can anyone tell me how can i see or debug API response in Logcat? i put Log.d("response",response.toString()) but not getting anything ... but Toast being shown with a response. – pankaj Apr 20 '20 at 22:09
-1

this is an example uses StringRequest

    StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {  
    @Override  
    protected Map<String, String> getParams() throws AuthFailureError {  
        Map<String, String> map = new HashMap<String, String>();  
        map.put("api_key", "12345");  
        map.put("ts_code", "12345");  
        return map;  
    }  
}; 
VVN
  • 1,607
  • 2
  • 16
  • 25
Ricky.Lee
  • 9
  • 2
  • How does this solve the problem? The body of the POST request is json. – OBX Oct 17 '16 at 06:01
  • @Ricky.Lee i am not asking api_key and ts_code .api_key and ts_code add url link its working fine.. i am asking about json data like trip [ {}] – Pawandeep Oct 17 '16 at 06:06
-3
 OkHttpClient okHttpClient = new OkHttpClient();   
 ContentValues values = new ContentValues();
            values.put(parameter1Name, parameter1Value);
            values.put(parameter2Name, parameter2Value);

            RequestBody requestBody = null;

            if (values != null && values.size() > 0) {
                FormEncodingBuilder formEncoding = new FormEncodingBuilder();

                Set<String> keySet = values.keySet();
                for (String key : keySet) {
                    try {
                        values.getAsString(key);
                        formEncoding.add(key, values.getAsString(key));

                    } catch (Exception ex) {
                        Logger.log(Logger.LEVEL_ERROR, CLASS_NAME, "getRequestBodyFromParameters", "Error while adding Post parameter. Skipping this parameter." + ex.getLocalizedMessage());
                    }
                }
                requestBody = formEncoding.build();
            }

            String URL = "http://example.com";
            Request.Builder builder = new Request.Builder();
            builder.url(URL);
            builder.post(requestBody);
            Request request = builder.build();
            Response response = okHttpClient.newCall(request).execute();
Pruthviraj
  • 560
  • 6
  • 23
  • i just post these value { "trips": [ { "departure_code": "SYD", "arrival_code": "LON", "outbound_date": "2014-01-24", "inbound_date": "2014-01-29" } ], "adults_count": 1, "locale": "ar" } – Pawandeep Oct 17 '16 at 06:40
  • @Pawandeep Kaur has asked for volley body post parameters and not Okhttp, where both are completely different libraries in their format – Anup Jun 19 '17 at 14:02