Retrofit-入门使用

1. 在模块目录下的build.gradle

dependencies {
    compile "com.squareup.retrofit2:retrofit:2.1.0"
    compile "com.squareup.retrofit2:converter-gson:2.1.0"
}

2. 请求服务接口类-注解对应服务器接口

public interface HttpService {

    String SERVER_HOST = "http://xx.xx.xx.xx";
    String CONTENT_PATH = "/xx";

    class factory {

        private static volatile HttpService instance;

        public static HttpService getHttpService() {
            if (instance == null) {
                synchronized (HttpService.class) {
                    if (instance == null) {
                        Retrofit rf = new Retrofit.Builder().baseUrl(HttpService.SERVER_HOST).build();
                        HttpService hs = rf.create(HttpService.class);
                        instance = hs;
                    }
                }
            }
            return instance;
        }
    }

    @GET(CONTENT_PATH + "/api/app/list?type=sense")
    Call<ResponseBody> list(@Header("DAAUTH") String token);

    @GET(CONTENT_PATH + "/api/app/navlist?type=sense")
    Call<ResponseBody> favlist(@Header("DAAUTH") String token);

    @GET(CONTENT_PATH + "/api/app/fav?type=sense")
    Call<ResponseBody> fav(@Header("DAAUTH") String token, @Query("appid") String appid);

    @GET(CONTENT_PATH + "/api/app/unfav?type=sense")
    Call<ResponseBody> unfav(@Header("DAAUTH") String token, @Query("appid") String appid);

    @GET(CONTENT_PATH + "/api/auth/login/")
    Call<ResponseBody> loginByBasic(@Header("DAAUTH") String basic);

    @GET(CONTENT_PATH + "/api/auth/login/")
    Call<ResponseBody> loginByToken(@Header("DAAUTH") String token);

}

这里采用了一个单例模式,在定义的接口服务类中声明一个内部类factory来定义与返回HttpService的单例,内部直接使用了Retrofit进行创建。

3.具体调用

HttpService hs = HttpService.factory.getHttpService();
String token = "token 5cd61e10d242937a13ec40f671db19d5";
Call
<ResponseBody> call = hs.list(token); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { ResponseBody body = response.body(); if (body != null) { Log.d(TAG, body.string()); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { if(t.getClass().equals(SocketTimeoutException.class)) { Toast.makeText(MainActivity.this, "Connect Timeout...", Toast.LENGTH_SHORT).show(); String msg = t.getMessage(); Log.e(TAG, msg); } } });

简单的使用方法,Retrofit有更多的接口方法可供使用。

 

posted @ 2017-07-17 15:57  清风@_@  阅读(182)  评论(0编辑  收藏  举报