实战retrofit

retrofit 是一个类型安全的 REST 客户端,用于 Android 平台。

上次项目因为时间关系并没有来得及用上retrofit这个据说比volley(因为我之前项目是用的volley)更快捷的。这周翻看了网上一些资料学习了,并总结了一下。

首先,配置。方法在as添加,就不细说了。(retrofit 2.0)

接下来就看使用方法 (ApiService)

@POST("login")
    Call<LoginResult> getLogin(@Query("phone") String phone, @Query("password") String password);   

@POST是请求方法。里面包含的则是对应的接口。Call方法里面是返回的数据。@Query 是添加查询 。

Retrofit的Annotation包含请求方法相关的@GET、@POST、@HEAD、@PUT、@DELETA、@PATCH,和参数相关的@Path、@Field、@Multipart等。

注意:@GET 等请求不要以/开头;@Url: 可以定义完整url,不要以 / 开头。

然后是一个总的用法。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
LoginService loginService = retrofit.create(LoginService.class);

这里的baseUrl是接口前缀。addConverterFactory(GsonConverterFactory.create(gson))是转换器,提供Gson支持,可以添加多种序列化Factory,但是GsonConverterFactory必须放在最后,否则会抛出异常。 然后到2.0移除了Converter,所以需要自己插入一个Converter 不然的话Retrofit 只能接收字符串结果。同样的,2.0也不再依赖于Gson。2.0之后网络请求可以取消。

Call loginResultCall = loginService.getLogin(phone,password);
taskListsResultCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
Log.e(“h”, “成功” + response.body());
}
}@Override
public void onFailure(Call call, Throwable t) {
Log.e(“h”, “失败”);
}
});

当然如果想要实现拦截器和超时设置就需要依赖okhttp。以下是我写的一个调用类。写的并不好,不喜勿喷。

import com.app.spire.BuildConfig;
import com.app.spire.network.url.ApiUrl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by huyin on 16/7/10.
 */
public class AppClient {
    public static Retrofit retrofit = null;

    public static Retrofit retrofit() {
        if (retrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            /**
             *  公共参数
             */
            Interceptor addQueryParameterInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    Request request = null;
                    String method = originalRequest.method();
                    Headers headers = originalRequest.headers();
                    HttpUrl modifiedUrl = originalRequest.url().newBuilder()
                            .addQueryParameter("参数1", "")
                            .addQueryParameter("参数2", "")
                            .build();
                    request = originalRequest.newBuilder().url(modifiedUrl).build();
                    return chain.proceed(request);
                }
            };
            builder.addInterceptor(addQueryParameterInterceptor);

            /**
             * Log信息拦截器
             */
            if (BuildConfig.DEBUG) {
                // Log信息拦截器
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                //设置 Debug Log 模式
                builder.addInterceptor(loggingInterceptor);
            }
            /**
             * 设置超时和重连
             */
            //设置超时
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(10, TimeUnit.SECONDS);
            builder.writeTimeout(10, TimeUnit.SECONDS);
//            builder.retryOnConnectionFailure(true);//错误重连

            OkHttpClient okHttpClient = builder.build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(ApiUrl.getHeadUrl())
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())//转换器
                    .build();
        }
        return retrofit;

    }
}

import com.app.spire.network.result.BaseResult;
import com.app.spire.util.ActivityUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
* Created by huyin on 16/7/10.
*/
public class BaseRequest {
private Call mCall;

public BaseRequest( Call call) {
    mCall = call;
}

//异步请求
public void handleResponse(final ResponseListener listener) {
    mCall.enqueue(new Callback<T>() {

        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if (response.raw().code() == 200) {//200是服务器有合理响应
                if (response.isSuccessful() && response.errorBody() == null) {
                    listener.onSuccess(response.body());
                } else {
                    listener.onFail();
                }
            } else {//失败响应
                onFailure(call, new RuntimeException("response error,detail = " + response.raw().toString()));
            }
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            if (t instanceof SocketTimeoutException) {
                ActivityUtils.toast("连接超时!");
            } else if (t instanceof ConnectException) {
                ActivityUtils.toast("网络出错");
            } else if (t instanceof RuntimeException) {

            }
        }
    });
}

// 取消
public void cancel(){
    mCall.cancel();
}


public interface ResponseListener<T> {
    void onSuccess(BaseResult t);

    void onFail();
}

}
未完待续…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值