如何使用Volley发送带有JSON主体的POST请求? [英] How to send a POST request with JSON body using Volley?

查看:122
本文介绍了如何使用Volley发送带有JSON主体的POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用volley库将这些参数传递给post方法。查看链接和屏幕短片
JSON STRUCTURE
url: - POST api.wego.com/flights/api/k/2/searches?api_key=12345&ts_code=123

How to pass these parameter into post method using volley library .see link and screen short JSON STRUCTURE url:- POST api.wego.com/flights/api/k/2/searches?api_key=12345&ts_code=123

发布参数: -
链接: - http://support.wan.travel/hc/en-us/articles/200191669-Wego-Flights-API 。我厌倦了,但又面临错误。

Post parameters:- link :- http://support.wan.travel/hc/en-us/articles/200191669-Wego-Flights-API. i tired 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");


推荐答案

通常的方法是使用带键值对的 HashMap 作为Volley的请求参数

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.

选项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);




注意:HashMap可以将自定义对象作为值

NOTE: A HashMap can have custom objects as value

选项2:

在请求正文中直接使用JSON

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

这篇关于如何使用Volley发送带有JSON主体的POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆