Retrofit 网络访问框架简单使用

1.引入远程依赖:包括okhttp;retrofit2;retrofit的GSON解析器

compile'com.squareup.okhttp3:okhttp:3.2.0'
compile'com.squareup.retrofit2:retrofit:2.0.2'
compile'com.squareup.retrofit2:converter-gson:2.0.2'

2.初始化okhttpclient(可以设置更多的okhttp参数):

OkHttpClient client=new OkHttpClient();

 

  若没有初始化okhttp,retrofit默认也是使用okhttp的

3.创建Retrofit

Retrofit retrofit=new Retrofit.Builder()
//设置OKHttpClient
.client(client)
//设置baseUrl,注意,baseUrl必须后缀"/"
.baseUrl("http://api.1396app.com/")
//添加Gson转换器
.addConverterFactory(GsonConverterFactory.create())
.build();

4.创建请求服务接口(一个HTTPGET请求)

public interface GitHubAPI{
  @GET("api/app/version")//这里是跟在baseurl后面的,拼接起来完整的url=http://api.1396app.com/api/app/version
  Call<AppEntity> retrofitGet(@Query("id") String id);
}

   说明:@GET:声明为HTTPGET访问方式;@GET()里面是访问的url,是跟baseurl合在一起的;AppEntity是一个javabean,存放改接口放回的数据;@Query是Get请求的一种方式;@Query("id"),id是传入的参数;后面String id,id是参数值。
  那么拼起来完整的URL=http://api.1396app.com/api/app/version?id=203(@Query表示了?pargram=203 ,这种Get请求方式)

5.在Acitivity中进行网络请求

GitHubAPI gitHubAPI=retrofit.create(GitHubAPI.class);
private void httpGet(GitHubAPI gitHubAPI){
  Call<AppEntity> httpGet=gitHubAPI.retrofitGet("592");
  httpGet.enqueue(new Callback<AppEntity>(){
  @Override
  public void onResponse(Call<AppEntity> call,Response<AppEntity> response){
  AppEntity appEntity=response.body();
  Log.e("MainActivity",response.toString());
    }

  @Override
  public void onFailure(Call<AppEntity>call,Throwablet){
  Log.e("MainActivity","false");
    }
  });
}

 更多:还在继续学习

Retrofit项目主页: http://square.github.io/retrofit/?spm=5176.100239.blogcont26705.4.HvebZh#introduction

Retrofit2 完全解析 探索与okhttp之间的关系:http://blog.csdn.net/lmj623565791/article/details/51304204

转载于:https://www.cnblogs.com/caoRM/p/5803638.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值