How to send a POST request with JSON body using Volley?

前端 未结 3 1897
余生分开走
余生分开走 2020-12-05 11:37

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
Scre

相关标签:
3条回答
  • 2020-12-05 12:17

    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();
    }
    
    0 讨论(0)
  • 2020-12-05 12:26
     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();
    
    0 讨论(0)
  • 2020-12-05 12:28

    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;  
        }  
    }; 
    
    0 讨论(0)
提交回复
热议问题