Retrofit的使用

Retrofit是一款很有创意的开源网络框架,因为其简单与出色的性能,Retrofit 是安卓上最流行的且很有创意的开源网络框架之一。,Square公司为Android开源的类型安全的Http客户端;底层基于OkHttp,使用OkHttp客户端;让用户自定义接口,将java API的定义转换为interface形式;使用注解对接口进行解析和调用;支持配置json解析器;Retrofit源码下载地址:https://github.com/square/retrofit

1.添加依赖

   compile 'com.squareup.retrofit2:retrofit:2.1.0'
   compile 'com.squareup.retrofit2:converter-gson:2.0.2'

2.创建Retrofit实例对象

 Retrofit retrofit = new Retrofit.Builder().
           //设置服务器主机  服务器主机应该以/结束, 否则会报错
           baseUrl("http://192.168.31.101:8080/apitest/")
           //配置Gson最为json的解析器
          .addConverterFactory(GsonConverterFactory.create())
          .build();

3.定义业务逻辑接口

 public interface StuApi {
    //使用GET定义一个业务方法,获取类表信息
    @GET("test")
    Call<User> getOrder();
 }

4 创建接口实例对象

 stuApi = retrofit.create(StuApi.class);

5.获取业务方法的调用对象,并进行请求

//调用接口的 方法获取call对象,此时只是获取了http请求信息的封装独享,就是Call对象
        //当时此时还未执行http请求
        Call<User> useOrder = stuApi.getOrder();

        /**Response<User> response = useOrder.execute();
        User user = response.body();
        tv.setText(user.nickname);
        //以上的代码会阻塞UI线程,因此不能在安卓的主线程中调用,不然会面临NetworkOnMainThreadException。如果你想调用execute方法,请在后台线程执行。**/
        //异步执行业务方法
        useOrder.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                //response就是响应结果的封装对象
                User body = response.body();
                tv.setText(body.nickname+body.gender);
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                tv.setText(t.getMessage());

            }
        });
    }

6.使用POST注解

  //使用POST注解,进行post请求,登录的接口,提交key-value数据
    @FormUrlEncoded //如果没有这句会报错@Field parameters can only be used with form encoding
    @POST("login")
    Call<People> login(@Field("username")String p1,@Field("password")String p2);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值