Android网络框架-Volley(四) 使用get和post方法发送json请求

这一篇文章起我们开始介绍如何使用Volley发起请求,其中的例子有一部分我借用了Ravi Tamada博客中的例子。Ravi Tamada写了好多很高质量的文章,如果有兴趣的朋友可以去他的博客学习一下:Android working with Volley Library。通过前面的分析我们知道Volley发送请求的前提是我们得建立一个RequestQueue。在Android网络框架-Volley(二) RequestQueue源码分析以及建立一个RequestQueue中我们介绍了如何创建一个单例的RequestQueue,如果不会的朋友可以看一下。

发出JSON请求

Volley提供给我们发送JSON请求的类--JsonRequest。我们不能直接使用它,它是一个抽象类,他有两个子类:JsonObjectRequest和JsonArrayRequest。我们使用这两个子类来发出json请求

使用JsonObjectRequest

// 给request赋一个TAG,以便于取消时候使用
String tag_json_obj = "json_obj_req";
 
String url = "http://api.androidhive.info/volley/person_object.json";
         
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();     
        //新建一个JsonObjectRequest实例
        //第一个参数是指定get还是post方式
        //第二个参数是要请求的地址
        //第三个参数是要传的参数,这里传null,后面解释
        //第四个参数是一个Listener接口,重写里面两个方法
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                url, null,
                new Response.Listener
   
   
    
    () {
                    //在这个方法里,成功获取到了数据
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {
                    //在这个方法里,打印错误信息
  
  • 1
    点赞
  • 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、付费专栏及课程。

余额充值