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

posted @ 2016-08-24 16:46  草人木  阅读(1309)  评论(0编辑  收藏  举报