使用POST请求获取json数组

时间:2015-04-02 21:43:15

标签: android json android-volley

我正在使用volley.jar从远程服务器获取JSON数组。能够通过GET请求获取。请帮我处理POST请求

我正在关注androidhive的教程。

这是我的工作代码。

public class fbuk extends Activity {

// Movies json url
    private static final String url = "http://example.com/xyz.php?q=ram";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_main);

        listView = (ListView) findViewById(R.id.listview);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);


        pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();



        JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

// Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("ttl"));
                            movie.setThumbnailUrl(obj.getString("img"));
                            movie.setRating(obj.getString("stts"));
                            movie.setYear(obj.getString("relz"));

                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
}

如何发送参数

2 个答案:

答案 0 :(得分:1)

public void Post(String url, final Map<String, String> map) {
    showProgress();
    RequestQueue queue = Volley.newRequestQueue(_serverctx);
    StringRequest request = new StringRequest(Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
           if (response!=null && response.length()>0) {
                try {

                    _response.result(new JSONObject(response)); // Pass data to your parsing method(in my case i made a interface)
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("error");
            hideProgres();
        }
    }){
        @Override
        protected Map<String, String> getParams() {
            return map;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    request.setShouldCache(false);
    request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
    queue.add(request);
}

从活动或片段

调用

将上述方法放在一个单独的类中并发出类似

的调用
Map<String,String> params = new HashMap<String, String>();
                    params.put("email",email);
                    params.put("password",password);
                     _req = new NetworkRequests(this, ctx);
                     _req.Post(ShoqahContants.Login_URL, params);

你完成了:)

答案 1 :(得分:1)

这对我有用。

   pDialog = new ProgressDialog(this);

    pDialog.setMessage("Loading...");
    pDialog.show();
    url="http://www.example.com/xyz.php";
    Volley.newRequestQueue(your_activity.this).add(
            new CustomJsonRequest(Request.Method.POST, url, null,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            hidePDialog();

   // Parsing json
                            for (int i = 0; i < response.length(); i++) {
                                try {

                                    JSONObject obj =    response.getJSONObject(i);
                                    GC gc = new GC();
                                    gc.setTitl(obj.getString("ttl"));

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            adapter.notifyDataSetChanged();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d("Error: " + error.getMessage());
                    hidePDialog();
                }
            }) {


                @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
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

public class CustomJsonRequest extends Request {

    Map<String, String> params;
    private Response.Listener listener;

    public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
                             Response.Listener responseListener, Response.ErrorListener errorListener) {

        super(requestMethod, url, errorListener);


        params=new HashMap<String, String>();
        params.put("key", value);
        this.params = params;
        this.listener = responseListener;
    }

    @Override
    protected void deliverResponse(Object response) {
        listener.onResponse(response);

    }

    @Override
    public Map<String, String> getParams() throws AuthFailureError {

        return params;
    }

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

p.s:json必须采用以下格式

 [{"titl":"The Great gatsby"},{"titl":"Wolf Of Wall Street"}]