使用android volley库发送JSONArray POST请求

时间:2015-02-22 10:35:55

标签: java android json http-post android-volley

我想发送和接收带有齐射的Json阵列。 现在我可以收到一个阵列但没关系,但我不知道如何发送请求(例如:使用post方法)。

JsonArrayRequest arrayReq = new JsonArrayRequest(URL,
            new Listener<JSONArray>() {
}

4 个答案:

答案 0 :(得分:2)

 List<Map<String,String>> listMap =  new ArrayList<Map<String, String>>();
        Map<String,String> map  = new HashMap<String,String>();
        try {

            map.put("email", customer.getEmail());
            map.put("password",customer.getPassword());

        } catch (Exception e) {
            e.printStackTrace();
        }
        listMap.add(map);

        String url = PersonalConstants.BASE_URL+"/url";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d(App.TAG, jsonObject.toString());
                    }
                }, new Response.ErrorListener (){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d(App.TAG,volleyError.toString());
            }
        }
        );
        App.getInstance().getmRequestQueue().add(jsonObjectRequest);

答案 1 :(得分:1)

以下是一个例子:

// Define the web service URL
final String URL = "http://www.someurl.com";

// POST params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "raha tamjid");

// Define the POST request
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
   new Response.Listener<JSONObject>() {
       @Override
       public void onResponse(JSONObject response) {
           try {
               VolleyLog.v("Response:%n %s", response.toString(4));
           } 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(req);

POST请求的不同之处在于它需要JSONObject作为参数。

编辑1:

如果您在IDE中安装了Volley作为库项目,那么只需定义一个新的构造函数

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
    Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
JsonArrayRequest库代码中出现的类Volley内的

。现在,您可以使用它来创建JsonArrayRequest个对象,并将它们添加到RequestQueue

编辑2:

1。here获取Volley图书馆项目。下载项目并在IDE中进行设置。

2。按照编辑1 中的讨论,对JsonRequest类(在com.android.volley.toolbox名称空间中找到)进行修改。

3。 APPLICATION PROJECT volley.jar文件夹中删除libs

4. 现在转到项目属性 - &gt; Android - &gt;图书馆并点击添加。从这里选择Volley项目。清洁&amp;重建。

5. 现在,在您的 APPLICATION PROJECT 中,您可以制作一个POST JsonArrayRequest,就像我们如何制作POST JsonObjectRequest并获得{ {1}}中的{1}}。

答案 2 :(得分:0)

创建一个类并扩展JsonArrayRequest然后覆盖

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("name", "value");
    return params;
}

and add a new constructor and in it call

super(Method.POST, url, null, listener, errorListener);

or use this class

public class PostJsonArrayRequest extends JsonRequest<JSONArray> {

    /**
     * Creates a new request.
     * @param url URL to fetch the JSON from
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, null, listener, errorListener);
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("name", "value");
        return params;
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}

答案 3 :(得分:0)

创建一个名为JsonArrayPostRequest的新java类,现在可以像上一个请求一样使用它,只需用JsonArrayPostRequest替换JSONArrayRequest并传递正确的参数

public  class JsonArrayPostRequest extends Request<JSONArray>{  
    private Map<String,String> mParam;  
    private Listener<JSONArray>  mListener;  


    public JsonArrayPostRequest(String url,Listener<JSONArray> listener, ErrorListener errorListener,Map param) {  
        super(Request.Method.POST, url, errorListener);  
        mListener=listener;  
        mParam=param;   
    }  
    @Override  
    protected Map<String, String> getParams() throws AuthFailureError {  
        return mParam;  
    }  

       @Override  
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {  
            try {  
                String jsonString =  
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));  
                return Response.success(new JSONArray(jsonString),  
                        HttpHeaderParser.parseCacheHeaders(response));  
            } catch (UnsupportedEncodingException e) {  
                return Response.error(new ParseError(e));  
            } catch (JSONException je) {  
                return Response.error(new ParseError(je));  
            }  
        }  

    @Override  
    protected void deliverResponse(JSONArray response) {  
        mListener.onResponse(response);  

    }  

} 

使用:

JsonArrayPostRequest request = new JsonArrayPostRequest(URL,new Response.Listener<JSONArray>(),             
                new Response.ErrorListener() ,params);