如何使用Volley发送带有JSON主体的POST请求?

时间:2016-10-17 05:40:14

标签: android http-post android-volley

如何使用Volley库将这些参数传递给POST方法。

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

我试过了,但又面临错误。

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");

有关API的详细信息,请访问here

3 个答案:

答案 0 :(得分:24)

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

与以下示例类似,您需要根据具体要求进行自定义。

选项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可以将自定义对象作为值

选项2:

在请求正文中直接使用JSON

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

答案 1 :(得分:0)

这是一个使用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;  
    }  
}; 

答案 2 :(得分:-3)

<div class="container">
    <% @players.each do |club, player| %>
    <div class="row team">
        <div class="col-md-2">
            <%= image_tag club.team.image %>
        </div>
        <div class="col-md-10">
            <div class="row">
            <% player.each do |p| %>
            <div class="col-md-3">
                <p><%= link_to p.name, player_path(p) %></p>
            </div>
            <% end %>
            </div>
        </div>
    </div>
    <% end %>
</div>