使用Volley提交Json数据post

使用以下代码的时候,getParams()传递post请求,根本没有用,只能在构造方法里面传递JsonObject。在servlet中只能使用request.getInputStream()来获取输入流。因为没有设置对象的键值对,所以getParameter()也是没有办法获取的。

        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST,"http://222.20.9.33:8080/NoteServer/note/test.jsp", jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, "response -> " + response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage(), error);
            }
        })
        {
            //注意此处override的getParams()方法,在此处设置post需要提交的参数根本不起作用
            //必须象上面那样,构成JSONObject当做实参传入JsonObjectRequest对象里
            //所以这个方法在此处是不需要的
//    @Override
//    protected Map<String, String> getParams() {
//          Map<String, String> map = new HashMap<String, String>();
//            map.put("name1", "value1");
//            map.put("name2", "value2");

//        return params;
//    }

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }
        };

如果要传递一个对象的list,那该如何实现。最简单的方法就是将list转换为Json格式的字符串,以StringRequest的方式提交给servlet。这时候还要讲post请求的头部信息,做一下修改,不然也是传递不过去的。
“Content-Type”, “application/x-www-form-urlencoded”

        RequestQueue mQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://222.20.9.33:8080/NoteServer/note/test.jsp",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TAG", response.toString().trim());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("params1", result);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {  
            //设置头信息,不设置的话传递的信息都是null
                Map<String, String> map = new HashMap<String, String>();
                map.put("Content-Type", "application/x-www-form-urlencoded");
                return map;

            }

        };
Person person = new Person("xxxx", "24");
        ArrayList<Person> listP = new ArrayList<Person>();
        listP.add(person);
        listP.add(person);

        System.out.println(person.getName());
        Gson json = new Gson();
        Type type = new TypeToken<ArrayList<Person>>() {
        }.getType();
        result = json.toJson(listP, type);

使用Gson来转换对象列表,然后将json字符串传递给后台。
在servlet中获取传递的参数值

    System.out.println(request.getParameter("params1"));
    这样一个对象列表就可以传递到servlet,然后再进行json数据的解析。

安卓中使用了Gson库,安卓中自带的json将对象转化为json的方法比较麻烦,这个就比较好用些。

注意:在使用的时候,之前没有将post请求头部信息,重写所以上传之后,获取的数据一直都是null

参考:http://well-lf.iteye.com/blog/1543807
http://blog.csdn.net/onlysnail/article/details/47905375
http://www.open-open.com/lib/view/open1407727047207.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 中进行 JSONPOST 和 GET 请求,可以使用 Android 所提供的 HttpUrlConnection 类或者 Volley 框架,以下分别介绍两种方法: 1. 使用 HttpUrlConnection 进行 POST 和 GET 请求: - POST 请求: ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(jsonParam.toString()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` - GET 请求: ```java URL url = new URL("http://example.com/api?param1=value1&param2=value2"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` 2. 使用 Volley 进行 POST 和 GET 请求: - POST 请求: ```java String url = "http://example.com/api"; JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonParam, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` - GET 请求: ```java String url = "http://example.com/api?param1=value1&param2=value2"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` 需要注意的是,以上代码仅为示例,具体实现需要根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值