网络三方库Volley,Okhttp,Retrofit

1.网络_Volley

  • 主页:https://android.googlesource.com/platform/frameworks/volley/

  • 特点:

    • 通信更快,更简单
    • 支持网络请求的排序,优先级处理
    • 支持网络请求的缓存
    • 多级别的取消请求
    • 扩展性强
  • 使用步骤:

    1. 创建RequestQueue
    2. 创建Request
    3. 添加Request到RequestQueue
  • 注意事项:

    • 如果自己编译Volley的话,compileSdkVersion需要<=22,这是因为在Android6.0中Google移除了httpClient相关的API
    • Volley仅适合用于通信频繁数据量小的网络操作
    • 大数据量的网络操作并不适合Volley
    • 生成的jar文件地址:

      • \build\intermediates\bundles\release\classes.jar
    • 生成的aar文件地址:

      • \build\outputs\aar
  • 使用步骤:

    1. 创建RequestQueue
    2. 创建Request对象
    3. 添加Request对象到RequestQueue中

2.网络_Okhttp

  • 主页: https://github.com/square/okhttp
  • 配置: 添加依赖 compile ‘com.squareup.okhttp3:okhttp:3.2.0’
  • 特点:

    • 支持HTTP/2 和 SPDY
    • 默认支持 GZIP 降低传输内容的大小
    • 支持网络请求的缓存
    • 当网络出现问题时,自动重试一个主机的多个 IP 地址
  • 使用步骤:

    1. 创建OkHttpClient对象
    2. 创建Request对象
    3. 添加Request对象到OkHttpClient对象中并执行请求.示例代码:

          OkHttpClient client=new OkHttpClient();
          RequestBody body = new FormBody.Builder()
                  .add("phone", "13812345678")// 构造请求的参数
                  .add("key", "daf8fa858c330b22e342c882bcbac622")// 构造请求的参数
                  .build();
          Request post_request = new Request.Builder()
                  .url(URL_POST)// 指定请求的地址
                  .post(body)// 指定请求的方式为POST
                  .build();
          client.newCall(post_request).enqueue(new Callback() {
              @Override
              public void onFailure(Call call, IOException e) {
                  // 请求失败的处理
              }
      
              @Override
              public void onResponse(Call call, Response response) throws IOException {   // 请求成功的处理
                  ResponseBody body = response.body();
                  String string = body.string();// 把返回的结果转换为String类型
                  // body.bytes();// 把返回的结果转换为byte数组
                  // body.byteStream();// 把返回的结果转换为流
              }
          });
      
  • 因为原生OkHttp的使用比较复杂,有一个包装过的工具项目okhttp-utils使用非常简单

3.网络_Retrofit

  • 主页: https://github.com/square/retrofit
  • 注意: 使用Retrofit的前提是服务器端代码遵循REST规范 !!!!!
  • 功能:
    • 效率非常高
    • 可以直接将结果转换称Java类
    • 主要是配合RxJava一起使用
  • 配置:

    • 添加Retrofit依赖: compile ‘com.squareup.retrofit2:retrofit:2.0.2’
    • 添加数据解析依赖,根据实际情况进行选择
      • Gson : com.squareup.retrofit2:converter-gson:2.0.2
      • Jackson : com.squareup.retrofit2:converter-jackson:2.0.2
      • Moshi : com.squareup.retrofit2:converter-moshi:2.0.2
      • Protobuf : com.squareup.retrofit2:converter-protobuf:2.0.2
      • Wire : com.squareup.retrofit2:converter-wire:2.0.2
      • Simple XML : com.squareup.retrofit2:converter-simplexml:2.0.2
  • 使用步骤:

    1. 利用http://www.jsonschema2pojo.org/创建数据模型
      地址栏:
      http://apis.juhe.cn/mobile/get?phone=13957114819&key=daf8fa858c330b22e342c882bcbac622
    2. 创建REST API 接口

      • 常用注解:

        • 请求方法:@GET / @POST / @PUT / @DELETE / @HEAD
        • URL处理

          • @Path - 替换参数

            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@Path("id") int groupId);
            
          • @Query - 添加查询参数

            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
            
          • @QueryMap - 如果有多个查询参数,把它们放在Map中

            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
            
      • 示例代码:

        public interface NetAPI {
            @GET("/users/{user}")
            public Call<GitModel> getFeed(@Path("user") String user);
        
            @GET("/service/getIpInfo.php")
            public Call<IPModel> getWeather(@Query("city")String city);
        }
        
    3. 创建Retrofit对象, 并发起请求.示例代码:

      // 构建Retrofit实例
      Retrofit retrofit = new Retrofit.Builder().
              baseUrl(API2).
              addConverterFactory(GsonConverterFactory.create()).
              build();
      // 构建接口的实现类
      IpAPI weatherAPI = retrofit.create(IpAPI.class);
      // 调用接口定义的方法
      Call<IPModel> weatherCall = weatherAPI.getWeather("8.8.8.8");
      // 异步执行请求
      weatherCall.enqueue(new Callback<IPModel>() {
          @Override
          public void onResponse(Call<IPModel> call, Response<IPModel> response) {
              IPModel model = response.body();
              System.out.println("country:" + model.getData().getCountry());
          }
      
          @Override
          public void onFailure(Call<IPModel> call, Throwable t) {
              System.out.println(t.toString());
          }
      });
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值