Retrofit的简单使用

一、Retorfit简介

Retorfit是一个功能强大的联网工具。可以看成是OKHttp+数据解析(json、xml等)的组合。

说明文档:http://square.github.io/retrofit/

GitHub:https://github.com/square/retrofit

二、使用手册

1.引入配置

添加Retrofit依赖:

compile'com.squareup.retrofit2:retrofit:2.1.0'

使用Gson进行数据解析

compile'com.google.code.gson:gson:2.2.4'

将Retorfit与Gson关联

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

使用步骤

创建Retorfit.Builder对象,通过Builder指定基本配置信息。

Retrofit.Builder builder = new Retrofit.Builder();

builder.baseUrl("http://localhost:8080/");

builder.addConverterFactory(GsonConverterFactory.create());

通过Builder构建Retorfit对象

Retrofit retrofit = builder.build();

配置链接和参数

public interface ResponseInfoAPI {

@GET("TakeoutService/login")

Call login(@Query("username") String username,@Query("password") String password);}

注:ResponseInfo是服务器回复数据封装成的对象。

测试链接http://localhost:8080/TakeoutService/login?username="mingzi"&password="y"

完整链接组合

ResponseInfoAPI api = retrofit.create(ResponseInfoAPI.class);

执行联网操作

Callcall =api.login(“itheima”,”bj”);

call.enqueue(new Callback() {

@Override

public voidonResponse(Response response, Retrofit retrofit) {

//

结果处理

}

@Override

public void onFailure(Throwable throwable) {

//

异常处理

}

});

请求方法:@GET /@POST

替换原则:

1、@Path -替换参数

@GET("/group/{id}/users")

public Call<list>groupList(@Path("id") int groupId);

2、@Query -添加查询参数

@GET("/group/{id}/users")

public Call<list>groupList(@Path("id") int groupId, @Query("sort") Stringsort);

3、@QueryMap -如果有多个查询参数,把它们放在Map中

@GET("/group/{id}/users")

public Call<list>groupList(@Path("id") int groupId, @QueryMap Map options);

<list
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值