zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ubuntu 12.04 LTS 如何使用更快的更新源
    虚拟机安装ubuntu问题解决办法
    云计算
    Hadoop多节点集群安装配置
    Apache Lucene学习笔记
    Struts2运行流程
    数据结构与算法分析 java语音描述(引论)
    事物与分布式事物原理实践
    Get,Post请求中文乱码问题有效解决方法
    Vue2.5开发去哪儿网App 第四章笔记 下
  • 原文地址:https://www.cnblogs.com/caoRM/p/5803638.html
Copyright © 2011-2022 走看看