您的位置:首页 > 理论基础 > 计算机网络

Retrofit(okhttp)的动态代理

2017-11-14 10:03 260 查看
 自己手动写一个代理模式

代码实现:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Created by czx on 2017/11/14.
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Get {
String value() default "";
}

定义一个接口
public interface INews {
@Get("http://www.qq.com")
String getQQ();

@Get("http://www.sina.com.cn")
String getSina();
}


写一个类
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
* Created by czx on 2017/11/14.
*/

public class Retrofit {
public <T> T create(Class<T> service){
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[]{service}, new InvocationHandler() {
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Get get = method.getAnnotation(Get.class);
if(get == null){
return null;
}
String url = get.value();
return http(url);
}
});
}
public String http(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
Call call = client.newCall(request);
Response response = call.execute();
return response.body().string();
}
}
main方法里:

Retrofit retrofit = new Retrofit();
INews news = retrofit.create(INews.class);
String html = news.getSina();
System.out.println(html);

OK。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态代理