zoukankan      html  css  js  c++  java
  • Okhttp、Volley和Gson的简单介绍和配合使用

    转载自:http://www.apkbus.com/home.php?mod=space&uid=784586&do=blog&id=61255

    1.okhttp是一个高效的、快速的被谷歌认可的,支持HTTP/2和SPDY
     
    volley是一个方便网络任务库,可以负责请求、加载、缓存等同步问题,也可以处理图片、JSON、文本操作起来比较简单
     
    gson是JSON序列化和反序列化(以上三个能相互间轻松使用主要还是因为okhttp是谷歌推荐的、volley是谷歌开发的、Gson是谷歌开发的
     
    2.okhttp的Get用法:
    首先下载jar包,jar包的下载地址我不在发链接!

    [代码]java代码:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    OkHttpClient client = new OkHttpClient();
     
     public void execute() throws Exception {
            Request request = new Request.Builder()
                    .url("http://www.apkbus.com/forum.php")
                    .build();
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                
                System.out.println(response.body().string());
            }
        }
    Android本身不允许UI做网络线程,要开启一个子线程;Okhttp支持异步线程并回调返回,上面的方法稍加改动即可:
     

    [代码]java代码:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    private void enqueue(){
            Request request = new Request.Builder()
                    .url("http://www.apkbus.com/forum.php")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
     
                }
     
                @Override
                public void onResponse(Response response) throws IOException {
                    //NOT UI Thread
                    if(response.isSuccessful()){
                        System.out.println(response.body().string());
                    }
                }
            });
        }
     
    Okhttp的post的用法:
     
    RequestBody formBody = new FormEncodingBuilder()
        .add("platform", "android")
        .add("name", "chace")
        .add("subject", "乾隆十八掌")
        .build();
     
        Request request = new Request.Builder()
          .url(url)
          .post(body)
          .build();
     
    Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
     
    这个代码是同步网络请求,异步就改成enqueue就行了。
     
    这个okhttp和gson的用法是整合于网络,不过写的清晰易懂
    json串:
    {
        "data": [
            {
                "appcontent": "1",
                "appname": "UC浏览器",
                "apppackagename": "com.UCMobile",
                "id": 1,
                "remark": "1"
            },
            {
                "appname": "支付宝",
                "apppackagename": "com.alipay.android.app",
                "id": 2
            },
            {
                "appname": "WPS",
                "apppackagename": "cn.wps.moffice_eng",
                "id": 3
            }
        ],
        "msg": "获取信息列表成功",
        "version": 2
    }
     
    建立javaBean:
    这是数组里面的属性:
    public class ApkInfo {  
        private String apppackagename;  
        private Integer id;  
        private String appname;  
        private String appcontent;  
        private String remark;  
        public String getApppackagename() {  
            return apppackagename;  
        }  
      
        public void setApppackagename(String apppackagename) {  
            this.apppackagename = apppackagename;  
        }  
      
        public Integer getId() {  
            return id;  
        }  
      
        public void setId(Integer id) {  
            this.id = id;  
        }  
      
        public String getAppname() {  
            return appname;  
        }  
      
        public void setAppname(String appname) {  
            this.appname = appname;  
        }  
      
        public String getAppcontent() {  
            return appcontent;  
        }  
      
        public void setAppcontent(String appcontent) {  
            this.appcontent = appcontent;  
        }  
      
        public String getRemark() {  
            return remark;  
        }  
      
        public void setRemark(String remark) {  
            this.remark = remark;  
        }  
      
        @Override  
        public String toString() {  
            return "ApkInfo [id=" + id + ", remarm="  
                    + remark + ", appname=" + appname + ", appcontent=" + appcontent  
                    + ", apppackagename=" + apppackagename + "]";  
          
        }  
    }  
     
    这是外部集合的属性:
    public class PackageListInfo {  
        private String msg;  
        private String version;  
        private List<Object> data;  
      
        public String getMsg() {  
            return msg;  
        }  
          
        public void setMsg(String msg) {  
            this.msg = msg;  
        }  
          
        public String getVersion() {  
            return version;  
        }  
          
        public void setVersion(String version) {  
            this.version = version;  
        }  
          
        public List<Object> getData() {  
            return data;  
        }  
      
        public void setData(List<Object> data) {  
            this.data = data;  
        }  
          
        @Override  
        public String toString() {  
            return "PackageListInfo [version=" + version + ", data=" + data + ", msg=" + msg  
                    + "]";  
        }  
      
    }  
     
    新建一个OKHTTP的管理类get得到JSON数据,并进行处理。
    import android.util.Log;  
    import okhttp3.Call;  
    import okhttp3.Callback;  
    import okhttp3.OkHttpClient;  
    import okhttp3.Request;  
    import okhttp3.Response;  
      
    public class GetApkPackage {  
      
        public static String apkPackageUrl = http://192.168.10.133:8080/getAppInfor;  
          
        public static GetApkPackage install = new GetApkPackage();  
          
        public static ArrayList<String> appList=new ArrayList<String>();  
          
        public void getPackage() {  
            OkHttpClient mOkHttpClient = new OkHttpClient();  
            final Request request = new Request.Builder().url(apkPackageUrl).build();  
            mOkHttpClient.newCall(request).enqueue(new Callback() {  
      
                @Override  
                public void onFailure(Call call, IOException e) {  
                    System.out.println("获取apk列表失败");  
                    Log.d("GetApkPackage", e.getMessage());  
                      
                }  
                @Override  
                public void onResponse(Call call, Response response) throws IOException {  
                    String result = response.body().string();  
                    System.out.println(result);  
                    //InputStream is = response.body().byteStream();  
                    //byte[] bytes = response.body().bytes();  
                    Gson gson = new Gson();  
                    PackageListInfo packlist = gson.fromJson(result,PackageListInfo.class);  
                      
                    System.out.println(packlist.getData().toString());  
                    List<ApkInfo> apkList = new ArrayList<ApkInfo>();  
                    Type type = new TypeToken<ArrayList<ApkInfo>>() {}.getType();  
                    apkList = gson.fromJson(packlist.getData().toString(), type);  
                    /* 
                    Map<String,ApkInfo> apkList = gson.fromJson(packlist.getData().toString(),   
                            new TypeToken<List<ApkInfo>>() {   
                            }.getType()); 
                    */  
                    if(apkList == null){  
                        System.out.println("apkpackage列表为空");  
                        return;  
                    }  
                    for(int i =0;i<apkList.size();i++){    
                          String apkName = apkList.get(i).getApppackagename();  
                          System.out.println(apkName);   
                          appList.add(apkName);  
            
                  }   
                }  
            });  
        }  
          
        public static GetApkPackage getInstall(){         
            return install;  
        }  
      
    }  
    上述代码中,对JSON数据的处理看起来很简单,只要new一个GSON实例,然后通过gson.fromJson方法,就能够得到json数据
    [java] view plain copy 在CODE上查看代码片派生到我的代码片
    Gson gson = new Gson();  
    PackageListInfo packlist = gson.fromJson(result,PackageListInfo.class); 
     
    OKHTTP发送一个字符串给服务器的实例如下:
    [java] view plain copy 在CODE上查看代码片派生到我的代码片
    public final class PostString {  
      public static final MediaType MEDIA_TYPE_MARKDOWN  
          = MediaType.parse("text/x-markdown; charset=utf-8");  
      
      private final OkHttpClient client = new OkHttpClient();  
      
      public void run() throws Exception {  
        String postBody = ""  
            + "Releases "  
            + "-------- "  
            + " "  
            + " * _1.0_ May 6, 2016 "  
            + " * _1.1_ June 15, 2016 "  
            + " * _1.2_ August 11, 2016 ";  
      
        Request request = new Request.Builder()  
            .url("https://192.168.10.133:8080/base")  
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))  
            .build();  
      
        Response response = client.newCall(request).execute();  
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
      
        System.out.println(response.body().string());  
      }  
      
      public static void main(String... args) throws Exception {  
        new PostString().run();  
      }  
    }  
     
    3.Volley的用法:
    Volley提供了JsonObjectRequest、JsonArrayRequest、StringRequest等Request形式。
    JsonObjectRequest:返回JSON对象。
    JsonArrayRequest:返回JsonArray。
    StringRequest:返回String,这样可以自己处理数据,更加灵活。
     
    我们创建一个StringRequest:
    StringRequest stringRequest = new StringRequest("http://www.apkbus.com/forum.php",  
                            new Response.Listener<String>() {  
                                @Override  
                                public void onResponse(String response) {  
                                    Log.d("TAG", response);  
                                }  
                            }, new Response.ErrorListener() {  
                                @Override  
                                public void onErrorResponse(VolleyError error) {  
                                    Log.e("TAG", error.getMessage(), error);  
                                }  
                            });  
     
    这篇主要还是简单了介绍了三者的关系和用法
  • 相关阅读:
    Asynchronous AOF fsync is taking too long (disk is busy?). Writing the AOF buffer without waiting for fsync to complete, this may slow down Redis.
    DHCP "No subnet declaration for xxx (no IPv4 addresses)" 报错
    Centos安装前端开发常用软件
    kubernetes学习笔记之十:RBAC(二)
    k8s学习笔记之StorageClass+NFS
    k8s学习笔记之ConfigMap和Secret
    k8s笔记之chartmuseum搭建
    K8S集群集成harbor(1.9.3)服务并配置HTTPS
    Docker镜像仓库Harbor1.7.0搭建及配置
    Nginx自建SSL证书部署HTTPS网站
  • 原文地址:https://www.cnblogs.com/android-blogs/p/5867624.html
Copyright © 2011-2022 走看看