【原创】Android Retrofit学习之旅

1、依赖 build.gradle

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

2、权限

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

3、获取api数据的地址,我从网上找了一个获取天气的地址,如下:

https://www.apiopen.top/weatherApi?city=海口

看这个地址就是可以用get方法来获取。

以上这些准备好了,我们就开始Retrofit的学习,刚开始我也是摸不着头发,感觉好深奥,可能是菜鸟的原因,决定从最基础的入手。

首先我新建一个接口:获取天气的api

WeatherApi.class

public interface WeatherApi {
    @GET("weatherApi?city=海口")
    Call<ResponseBody> getWeatherInfo();
}

Retrofit提供的请求方式注解有@GET和@POST等,分别代表GET请求和POST请求,上面用的是GET请求,访问的地址是:“weatherApi?city=海口”。另外定义getWeahterInfo()方法,这个方法返回的类型Call<ResponseBody>。

然后我们创建Retroit

Retrofit retrofit = new Retrofit.Builder.baseUrl("https://www.apiopen.top/")
.addConverterFactory(GsonConverterFactory.create()).build();

WeatherApi weatherApi = retrofit.create(WeatherApi.class);

Call<ResponseBody> call = weatherApi.getWeatherInfo();

Retrofit是通过建造者模式构建出来的,请求的url是拼接而成,它是由baseUrl传入的URL加上请求网络接口的@GET("weatherApi?city=海口")中的URL拼接而成的,接下来用Retrofit的create方法动态代理获取到之前定义的接口,并调用该接口定义的getWeatherInfo()方法得到Call对象。 接下来用Call请求网络并处理回调,代码如下:

call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String body = null;
                try {
                    body = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ToastUtils.showLong(body);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

请求是异地请求网络,回调的CallBack是运行在UI线程,得到返回的response.body()就是一个json串,我们用string()打印出来,用Toast显示看看。如果想同步,请用call.execute();如果想中断网络,请用call.cancel()。

 

 

如有转载,请表明出处

posted @ 2018-06-10 09:35  施行  阅读(117)  评论(0编辑  收藏  举报