1、对于一个api调用,上层接口是如何设计的呢?对于大多数API调用者来说,希望上层调用非常简单,不希望知道太多的细节。在我们进行设计的时候,也是需要把最简单的接口设计在最上面。Retrofit网络框架上层调用是非常简单的,只需要创建一个这样的对象就可以进行网络请求,它的上层调用者可以指定线程池是什么、从网络获得的数据需要转换成什么样的数据,转换成json还是转换成RXJava,这就是Retrofit上层所提供的功能,我们的框架也这样设计接口。
2、将包名http改为nice
创建一个类NiceClient,这是对上层所提供的一些功能。
首先,需要这个NiceClient是通过Build方式来构建的。这个class中需要提供哪些参数呢?首先肯定有相关的url、可以指定请求的方式(通过urlconnection还是okhttp)、可以指定它的线程池是什么、指定转换器convert是什么
package com.nice;
import com.nice.convert.Convert;
import com.nice.convert.JsonConvert;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author nate
*/
public class NiceClient {
private String mUrl;
private HttpClient mHttpClient;
private ExecutorService mExecutor;
private List<Convert> mConverts;
private HashMap<Method, MethodAnnotationProcess> mMethodCache = new HashMap<>();
public NiceClient(Builder builder) {
this.mUrl = builder.mUrl;
this.mConverts = builder.mConverts;
this.mExecutor = builder.mExecutor;
this.mHttpClient = builder.mHttpClient;
}
public String getUrl() {
return mUrl;
}
public HttpClient getHttpClient() {
return mHttpClient;
}
public ExecutorService getExecutor() {
return mExecutor;
}
public List<Convert> getConverts() {
return mConverts;
}
public <T> T create(Class<T> clazz) {
if (!clazz.isInterface()) {
throw new RuntimeException("clazz 必须是接口类型");
}
for (Method method : clazz.getMethods()) {
MethodAnnotationProcess process = new MethodAnnotationProcess(method, this);
process.invoke();
mMethodCache.put(method, process);
}
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new MethodInvocation(this, mMethodCache));
}
public static class Builder {
public static final int CONNECTION_TIME_OUT = 3000;
public static final int READER_TIME_OUT = 3000;
public static final int WRITE_TIME_OUT = 3000;
private String mUrl;
private HttpClient mHttpClient;
private ExecutorService mExecutor;
private List<Convert> mConverts;
public Builder url(String url) {
this.mUrl = url;
return this;
}
public Builder executor(ExecutorService executorService) {
this.mExecutor = executorService;
return this;
}
public NiceClient build() {
List<Convert> converts = new ArrayList<>();
converts.add(new JsonConvert());
this.mConverts = converts;
if (mHttpClient == null) {
mHttpClient = new HttpClient.Builder().
setConnectionTimeOut(CONNECTION_TIME_OUT).
setReaderTimeOut(READER_TIME_OUT).
setWriteTimeOut(WRITE_TIME_OUT).
setExecutors(Executors.newCachedThreadPool()).
setConverts(converts).
builder();
// setHttpDns(new DefaultHttpDns()).
// setHostnameVerifier(HttpClient.Builder.DEFAULT_HOST_NAME_VERIFIER).
// setSSLSocketFactory(HttpClient.Builder.DEFAULT_SSL_SOCKET_FACTORY).
}
return new NiceClient(this);
}
}
}