标签:
public interface CallAdapter<T> { Type responseType(); //该请求适配器返回的数据类型 <R> T adapt(Call<R> call); //该请求适配器对原始Call的再次封装,如Call<R>到Observable<R>,这里的Call<R>在retrofit2中都是OkHttpCall对象 abstract class Factory { public abstract CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit); //获取网络请求适配器 protected static Type getParameterUpperBound(int index, ParameterizedType type) { return Utils.getParameterUpperBound(index, type); } //Example:完成Map<String, ? extends Runnable> 到 Runnable的转变;第i个参数的最上层的数据类型 protected static Class<?> getRawType(Type type) { return Utils.getRawType(type); } //Example:完成List<? extends Runnable> 到 List.class的转变; 即得到最外层的那个数据类型 } } public interface Converter<F, T> { T convert(F value) throws IOException; abstract class Factory { public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } //对响应数据的转换 public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return null; } //对请求数据的转换 public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } //String类型转换 } }
final Executor callbackExecutor; ExecutorCallAdapterFactory(Executor callbackExecutor) { this.callbackExecutor = callbackExecutor; }
public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Call.class) { return null; } final Type responseType = Utils.getCallResponseType(returnType); return new CallAdapter<Call<?>>() { @Override public Type responseType() { return responseType; } @Override public <R> Call<R> adapt(Call<R> call) { return new ExecutorCallbackCall<>(callbackExecutor, call); } //note1 }; }
final Executor callbackExecutor; //回调方法执行器 final Call<T> delegate;//网络请求实体 ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public boolean isExecuted() { return delegate.isExecuted(); } @Override public Call<T> clone() { return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone()); } @Override public Request request() { return delegate.request(); } @Override public Response<T> execute() throws IOException { return delegate.execute(); } //note1 @Override public void enqueue(final Callback<T> callback) {//note2 if (callback == null) throw new NullPointerException("callback == null"); delegate.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, final Response<T> response) { callbackExecutor.execute(new Runnable() { @Override public void run() { if (delegate.isCanceled()) { callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled")); } else { callback.onResponse(ExecutorCallbackCall.this, response); } } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onFailure(ExecutorCallbackCall.this, t); } }); } }); }
private final Scheduler scheduler; private RxJavaCallAdapterFactory(Scheduler scheduler) { this.scheduler = scheduler; } public static RxJavaCallAdapterFactory create() { return new RxJavaCallAdapterFactory(null); }
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { Class<?> rawType = getRawType(returnType); //note1 String canonicalName = rawType.getCanonicalName(); //note2 boolean isSingle = "rx.Single".equals(canonicalName); //note3 boolean isCompletable = "rx.Completable".equals(canonicalName); if (rawType != Observable.class && !isSingle && !isCompletable) { //note4 return null; } if (!isCompletable && !(returnType instanceof ParameterizedType)) { String name = isSingle ? "Single" : "Observable"; throw new IllegalStateException(name + " return type must be parameterized" + " as " + name + "<Foo> or " + name + "<? extends Foo>"); } if (isCompletable) { return CompletableHelper.createCallAdapter(scheduler); } CallAdapter<Observable<?>> callAdapter = getCallAdapter(returnType, scheduler); //note5 if (isSingle) { return SingleHelper.makeSingle(callAdapter); } return callAdapter; }
private CallAdapter<Observable<?>> getCallAdapter(Type returnType, Scheduler scheduler) { Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType); //note1 Class<?> rawObservableType = getRawType(observableType); //note2 if (rawObservableType == Response.class) { if (!(observableType instanceof ParameterizedType)) { throw new IllegalStateException("Response must be parameterized" + " as Response<Foo> or Response<? extends Foo>"); } Type responseType = getParameterUpperBound(0, (ParameterizedType) observableType); //note3 return new ResponseCallAdapter(responseType, scheduler); //note4 } if (rawObservableType == Result.class) { if (!(observableType instanceof ParameterizedType)) { throw new IllegalStateException("Result must be parameterized" + " as Result<Foo> or Result<? extends Foo>"); } Type responseType = getParameterUpperBound(0, (ParameterizedType) observableType); return new ResultCallAdapter(responseType, scheduler); //note5 } return new SimpleCallAdapter(observableType, scheduler); //note6 }
static final class SimpleCallAdapter implements CallAdapter<Observable<?>> { private final Type responseType; private final Scheduler scheduler; SimpleCallAdapter(Type responseType, Scheduler scheduler) { this.responseType = responseType; this.scheduler = scheduler; } @Override public Type responseType() { return responseType; } @Override public <R> Observable<R> adapt(Call<R> call) { Observable<R> observable = Observable.create(new CallOnSubscribe<>(call)) // note1 .lift(OperatorMapResponseToBodyOrError.<R>instance()); //note2 if (scheduler != null) { return observable.subscribeOn(scheduler); //note3 } return observable; } }
static final class CallOnSubscribe<T> implements Observable.OnSubscribe<Response<T>> { private final Call<T> originalCall; //note1 CallOnSubscribe(Call<T> originalCall) { this.originalCall = originalCall; } @Override public void call(final Subscriber<? super Response<T>> subscriber) { //note1.5 Call<T> call = originalCall.clone(); RequestArbiter<T> requestArbiter = new RequestArbiter<>(call, subscriber); //note2 subscriber.add(requestArbiter); subscriber.setProducer(requestArbiter); //note3 } }
static final class RequestArbiter<T> extends AtomicBoolean implements Subscription, Producer { private final Call<T> call; //构造该对象时传入的OkHttpCall private final Subscriber<? super Response<T>> subscriber; //构造该对象时传入的Subscriber<? super Response<T>> RequestArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) { this.call = call; this.subscriber = subscriber; } @Override public void request(long n) { if (n < 0) throw new IllegalArgumentException("n < 0: " + n); if (n == 0) return; // Nothing to do when requesting 0. if (!compareAndSet(false, true)) return; // Request was already triggered. try { Response<T> response = call.execute(); //note1 if (!subscriber.isUnsubscribed()) { subscriber.onNext(response); } //note2 } catch (Throwable t) { Exceptions.throwIfFatal(t); if (!subscriber.isUnsubscribed()) { subscriber.onError(t);} //note3 return; } if (!subscriber.isUnsubscribed()) { subscriber.onCompleted(); } //note4 } @Override public void unsubscribe() { call.cancel(); } //note5 @Override public boolean isUnsubscribed() { return call.isCanceled(); } //note6 }
final class OperatorMapResponseToBodyOrError<T> implements Operator<T, Response<T>> { private static final OperatorMapResponseToBodyOrError<Object> INSTANCE = new OperatorMapResponseToBodyOrError<>(); static <R> OperatorMapResponseToBodyOrError<R> instance() { return (OperatorMapResponseToBodyOrError<R>) INSTANCE; } @Override public Subscriber<? super Response<T>> call(final Subscriber<? super T> child) {//note1 return new Subscriber<Response<T>>(child) { @Override public void onNext(Response<T> response) { if (response.isSuccessful()) { child.onNext(response.body()); //note2 } else { child.onError(new HttpException(response)); //note3 } } @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } }; } }
String username = "sarahjean"; Observable<User> call = apiService.getUser(username); Subscription subscription = call .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<User>() { ...... @Override public void onError(Throwable e) { if (e instanceof HttpException) { HttpException response = (HttpException)e; //Line10 int code = response.code(); } } });
static final class ResponseCallAdapter implements CallAdapter<Observable<?>> { private final Type responseType; private final Scheduler scheduler; ResponseCallAdapter(Type responseType, Scheduler scheduler) { this.responseType = responseType; this.scheduler = scheduler; } @Override public Type responseType() { return responseType; } @Override public <R> Observable<Response<R>> adapt(Call<R> call) { Observable<Response<R>> observable = Observable.create(new CallOnSubscribe<>(call)); //note1 if (scheduler != null) { return observable.subscribeOn(scheduler); } return observable; } }
static final class ResultCallAdapter implements CallAdapter<Observable<?>> { private final Type responseType; private final Scheduler scheduler; ResultCallAdapter(Type responseType, Scheduler scheduler) { this.responseType = responseType; this.scheduler = scheduler; } @Override public Type responseType() { return responseType; } @Override public <R> Observable<Result<R>> adapt(Call<R> call) { Observable<Result<R>> observable = Observable.create(new CallOnSubscribe<>(call)) // note1 .map(new Func1<Response<R>, Result<R>>() { //note2 @Override public Result<R> call(Response<R> response) { return Result.response(response); } }).onErrorReturn(new Func1<Throwable, Result<R>>() { @Override public Result<R> call(Throwable throwable) { return Result.error(throwable); } }); if (scheduler != null) { return observable.subscribeOn(scheduler); } return observable; } }
public interface Converter<F, T> { T convert(F value) throws IOException; abstract class Factory { public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } //对响应数据的转换 public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return null; } //对请求数据的转换 public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } //String类型转换 } }
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { //note1 if (type == ResponseBody.class) { if (Utils.isAnnotationPresent(annotations, Streaming.class)) { return StreamingResponseBodyConverter.INSTANCE; } return BufferingResponseBodyConverter.INSTANCE; } if (type == Void.class) { return VoidResponseBodyConverter.INSTANCE; } return null; }
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { if (RequestBody.class.isAssignableFrom(Utils.getRawType(type))) { //note1 return RequestBodyConverter.INSTANCE; } return null; }
public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (type == String.class) { return StringConverter.INSTANCE; } return null; }
static final class StreamingResponseBodyConverter implements Converter<ResponseBody, ResponseBody> { static final StreamingResponseBodyConverter INSTANCE = new StreamingResponseBodyConverter(); @Override public ResponseBody convert(ResponseBody value) throws IOException { return value; } }
static final class BufferingResponseBodyConverter implements Converter<ResponseBody, ResponseBody> { static final BufferingResponseBodyConverter INSTANCE = new BufferingResponseBodyConverter(); @Override public ResponseBody convert(ResponseBody value) throws IOException { try { return Utils.buffer(value); } finally { value.close(); } } }
static final class VoidResponseBodyConverter implements Converter<ResponseBody, Void> { static final VoidResponseBodyConverter INSTANCE = new VoidResponseBodyConverter(); @Override public Void convert(ResponseBody value) throws IOException { value.close(); return null; } }
static final class RequestBodyConverter implements Converter<RequestBody, RequestBody> { static final RequestBodyConverter INSTANCE = new RequestBodyConverter(); @Override public RequestBody convert(RequestBody value) throws IOException { return value; } }
static final class StringConverter implements Converter<String, String> { static final StringConverter INSTANCE = new StringConverter(); @Override public String convert(String value) throws IOException { return value; } }
private final Gson gson; //操作实体 private GsonConverterFactory(Gson gson) { if (gson == null) throw new NullPointerException("gson == null"); this.gson = gson; } public static GsonConverterFactory create() { return create(new Gson()); } public static GsonConverterFactory create(Gson gson) { return new GsonConverterFactory(gson); }
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); //note1 return new GsonResponseBodyConverter<>(gson, adapter); }
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); //note1 return new GsonRequestBodyConverter<>(gson, adapter); }
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { private final Gson gson; private final TypeAdapter<T> adapter; GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) { this.gson = gson; this.adapter = adapter; } @Override public T convert(ResponseBody value) throws IOException { JsonReader jsonReader = gson.newJsonReader(value.charStream()); //note1 try { return adapter.read(jsonReader); } //note2 finally { value.close(); } } }
final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> { private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8"); private final Gson gson; private final TypeAdapter<T> adapter; GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) { this.gson = gson; this.adapter = adapter; } @Override public RequestBody convert(T value) throws IOException { Buffer buffer = new Buffer(); //note1 Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8); //note2 JsonWriter jsonWriter = gson.newJsonWriter(writer); adapter.write(jsonWriter, value); //note3 jsonWriter.close(); return RequestBody.create(MEDIA_TYPE, buffer.readByteString());//note4 } }
Response<T> parseResponse(okhttp3.Response rawResponse) { .... int code = rawResponse.code(); if (code < 200 || code >= 300) { //响应执行失败 ResponseBody bufferedBody = Utils.buffer(rawBody); return Response.error(bufferedBody, rawResponse); } if (code == 204 || code == 205) { //响应执行成功 但是没有返回数据body为空 return Response.success(null, rawResponse); } .... }
标签:
原文地址:http://blog.csdn.net/evan_man/article/details/51320637