retrofit2

Retrofit2是基于OkHttp的网络请求框架,通过注解的方式配置请求。

参考教程

首先自己写个网站页面info.php,简单的php,返回json格式字符串:


开启phpstudy后访问本机ip.info.php时页面上会显示{ "Employees": [ { "FirstName":"Bill" , "LastName":"Gates" }, { "FirstName":"George" , "LastName":"Bush" }, { "FirstName":"Thomas" , "LastName":"Carter" } ] }

android工程中添加依赖:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'		//解析gson

首先定义接口

public interface Emp {
        @GET("info.php")			//http使用get方法
        Call getinfo();	//定义getinfo方法,若有参数可在圆括号内添加如下形式的参数:@Query("city")  String city,即访问“ip.info.php?city=值”。返回值为Emplinfo类型,等会儿写	
    }

然后定义 Emplinfo类,####变量名需要和json里的名字相同↓↓↓####

public class Emplinfo{

        private List Employees;          //就是这里

        public List getEmployees() {
            return Employees;
        }

        public void setEmployees(List employees) {
            Employees = employees;
        }
    }

接着是Employee类,get和set省略了:

public class Employee{
        private String FirstName;
        private String LastName;
        。。。
    }

然后:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://********")					//自己的ip
                .addConverterFactory(GsonConverterFactory.create())			//设置 Json 转换器
                .build();
        Emp emp=retrofit.create(Emp.class);						//新建一个自定义的类的实例
        Call call = emp.getinfo();					//新建getinfo方法实例
        call.enqueue(new Callback() {					//执行,重写成功和失败方法
            @Override
            public void onResponse(Call call, Response response) {
                L.json(response.body().getEmployees()); 		//得到Employee数组

            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "Throwable : " + t);
            }
        });
  • 题外话,这里发现了https://github.com/fengzhizi715/SAF-Kotlin-log这个开源库打印日志挺好使的,logger打印自定义类还得重写tostring,这个L.json()挺清晰,就是首字母大小写有点问题。

然后看rxjava和retrofit结合

修改接口

    public interface Emp {
        @GET("info.php")
        Observable getinfo();
    }

还需要添加一个依赖,如果不添加会用rxjava的适配器而不是rxjava2的,不会提示语法错误,但是运行会报错空指针:

    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

请求改成如下:

 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://cyp.natapp1.cc/")//基础URL 建议以 / 结尾
                .addConverterFactory(GsonConverterFactory.create())//设置 Json 转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//RxJava 适配器             //新添加
                .build();
        Emp emp=retrofit.create(Emp.class);
        emp.getinfo().observeOn(AndroidSchedulers.mainThread())			//指定observer的回调方法运行在主线程
                .subscribeOn(Schedulers.io())						    //运行在io线程
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        L.d("onsubscribe");
                    }

                    @Override
                    public void onNext(Emplinfo emplinfo) {
                        L.json(emplinfo);
                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("onerror"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        L.d("oncomplete");
                    }
                });

成功输出。

06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ╔══════════════════════════════════════════════════════════════════════════════════════════════════
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║ Thread: main
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ╟──────────────────────────────────────────────────────────────────────────────────────────────────
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║ com.safframework.log.handler.ObjectHandler.handle  (ObjectHandler.kt:16)
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ╟──────────────────────────────────────────────────────────────────────────────────────────────────
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║ class com.example.myapplication.Test1$Emplinfo
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║ {
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║   "employees": [
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     {
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "firstName": "Bill",
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "lastName": "Gates"
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     },
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     {
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "firstName": "George",
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "lastName": "Bush"
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     },
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     {
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "firstName": "Thomas",
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║       "lastName": "Carter"
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║     }
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║   ]
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ║ }
06-26 09:15:27.410 3633-3633/com.example.myapplication I/System.out: ╚══════════════════════════════════════════════════════════════════════════════════════════════════

你可能感兴趣的:(Android开发,android开源库学习)