Retrofit学习一:小试牛刀

A type-safe HTTP client for Android and Java,一个针对Android和Java类型安全的http客户端。
类型安全是怎么解释呢,就是说Retrofit会把请求网络api返回的response转化为Java对象(实体类)方便操作,可以使用GsonFormat插件自动生成java对象,很方便额。
学习时,不需要自己搭建服务器(当然能自己搭建也行),我们可以用一些现有的api来测试,比如:http://gank.io/api(不需要注册,我喜欢)。测试访问http://gank.io/api/day/history接口。
这里写图片描述
一、在module的build.gradle中添加依赖

dependencies {
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' //retrofit库
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'  //gson解析库
}

二、定义参数接口
retrofit配置api参数是通过接口进行的

public interface ApiService {

    @GET("/{params}/day/history")
    Call<Date> getDate(@Path("params") String params);
}

此处把api作为参数,在调用时需要传入使得api完整。
三、定义响应实体
上图中的response是一个json数据,可以定义如下实体类进行接收


public class Date {
    private boolean error;
    private ArrayList<String> results;

    public boolean isError() {
        return error;
    }

    public ArrayList<String> getResults() {
        return results;
    }

    @Override
    public String toString() {
        return "error="+error+",results="+results.toString();
    }
}

四、请求数据

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://gank.io/") //域名
                .addConverterFactory(GsonConverterFactory.create()) //json转化器
                .build();
       ApiService service=retrofit.create(ApiService.class);   
       Call<Date> call2 = service.getDate("api");  //传入参数      
        call2.enqueue(new Callback<Date>() {
            @Override
            public void onResponse(Call<Date> call, Response<Date> response) {
                Log.i("MhahaainActivity", "onResponse(),," + response.body().toString());
            }

            @Override
            public void onFailure(Call<Date> call, Throwable t) {
                Log.i("MhahaainActivity", "Throwable=" + t.toString());
            }
        });
    }

这里使用了异步请求的enqueue方式,同步方式execute是线程堵塞的,需要新开一个线程进行处理。

结果:
Line 58669: 02-25 15:28:55.365 18249 18249 I MhahaainActivity: onResponse(),,error=false,results=[2017-02-24, 2017-02-23, 2017-02-22, 2017-02-21, 2017-02-20, 2017-02-17, 2017-02-16, 2017-02-15, 2017-02-14, 2017-02-13, 2017-02-10, 2017-02-09, 2017-02-08, 2017-02-07, 2017-02-06, 2017-02-04, 2017-02-03, 2017-01-23, 2017-01-22, 2017-01-20, 2017-01-19, 2017-01-16, 2017-01-13, 2017-01-12, 2017-01-11, 2017-01-10, 2017-01-09, 2017-01-06, 2017-01-05, 2017-01-04, 2017-01-03, 2016-12-30, 2016-12-29, 2016-12-28, 2016-12-27, 2016-12-26, 2016-12-23, 2016-12-22, 2016-12-21, 2016-12-20, 2016-12-19, 2016-12-16, 2016-12-15, 2016-12-14, 2016-12-13, 2016-12-12, 2016-12-09, 2016-12-08, 2016-12-07, 2016-12-06, 2016-12-05, 2016-12-02, 2016-12-01, 2016-11-30, 2016-11-29, 2016-11-28, 2016-11-25, 2016-11-24, 2016-11-23, 2016-11-22, 2016-11-21, 2016-11-18, 2016-11-17, 2016-11-16, 2016-11-15, 2016-11-14, 2016-11-11, 2016-11-10, 2016-11-09, 2016-11-08, 2016-11-07, 2016-11-04, 2016-11-03, 2016-11-02, 2016-11-01, 2016-10-31, 2016-10…

五、疑问
这里写图片描述
retrofit经常使用注释进行网络请求,比如上图中斜杠加的位置都有那么多讲究(推荐中间的方式),那么可以不使用注释吗?比如我就是单纯的想访问百度(www.baidu.com),就这么一个主体网址,后面并没有参数,那我现在怎么办呢?在apiService中可以这么做

@GET(".")
    Call<ResponseBody> simple();

引号中的点号表示你的 base URL 是一个全路径,不需要参数,不这样写的话会报如下错误:
Missing either @GET URL or @Url parameter
这个解决后,下面的代码还是报错java.lang.IllegalArgumentException: Illegal URL with retrofit

Retrofit retrofit = new Retrofit.Builder()
                //.baseUrl("http://gank.io")
                .baseUrl("www.baidu.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService service = retrofit.create(ApiService.class);

查下资料才知道需要在前面加上http:// or https://,血泪史啊,希望读者注意下。

当然,也可以直接在apiService中这么写全路径

 @GET("http://www.baidu.com/")
    Call<ResponseBody> simple();

此时baseUrl方法无效了。

参考文章:
1、http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0915/3460.html
2、http://blog.csdn.net/qq_17766199/article/details/49946429
3、http://blog.csdn.net/lmj623565791/article/details/51304204
4、http://www.tuicool.com/articles/NnuIva
5、http://blog.csdn.net/jdsjlzx/article/details/52015347

猜你喜欢

转载自blog.csdn.net/u013795543/article/details/57084232