平时常用的能访问网络的框架
Retrofit OkHttp XUtils Volley Afinal Android-async-http.......
平时项目是怎么做的?
UI: 下拉刷新 上拉加载,动画
网络: Retrofit+Rxjava okHttp Volley
数据库: GreenDao Armlite....
图片: Gild.....
使用别人的网络框架会有哪些问题
1.项目中有太多的代码不是我们需要的[本来10M可以写好的App却达到了200M的内存]
2.功能上不满足我们的需求[如Volley不支持大图 大文件 不支持切换线程]
开发一个网络访问框架考虑问题
1.框架的扩展性 不能只处理Json/Xml/image/file/audio/video...
2.框架的易用性 解一个小问题,只需调用一个到两个API
3.框架的稳定性/封装性/异常处理/模块化.........
4.框架和其他框架能否集成(数据库+网络+IOC注入+MVC架构+MVVM架构+资源加载.......)
需求
1.不关心数据解析 获取数据为对象
2.网络访问是在子线程完成 需要实现线程切换 操作可以放生在主线程[对于UI操作]
3.高并发
4.缓存,线程切换,资源价值..............VIP
框架逻辑
开始撸代码咯~~~~~~~~~~~~~~~~~~~~~~~~~
首先我们先手动加入fastJson包[libs/fastjson-1.2.2.jar]
方法一直接加入依赖:
implementation 'com.alibaba:fastjson:1.2.12'
方法二如图:
然后创建ThreadPoolManage(线程管理类)
在这里我们需要完成以下几点
1.将任务添加到请求队列中 [阻塞式队列]
2.把队列中的任务放入到线程池
3.让他们开始工作起来
//1.将任务添加到请求队列中 [阻塞式队列]
private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
//添加任务
public void execute(Runnable runnable) {
if (runnable != null) {
try {
queue.put(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//2.把队列中的任务放入到线程池
private ThreadPoolExecutor threadPoolExecutor;
private ThreadPoolManage() {
threadPoolExecutor = new ThreadPoolExecutor(4, 20, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(4), rejectedExecutionHandler);
// 开启传送带 让程序跑起来
threadPoolExecutor.execute(runnable);
}
// 拒绝策略
private RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//参数r就是超时的线程 如果超时就把它重新放回队列里
try {
queue.put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//3.让他们开始工作起来
private Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
Runnable runnable = null;
try {
//从队列取出请求
runnable = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 取到消息的话 就去执行
if (runnable != null) {
threadPoolExecutor.execute(runnable);
}
}
}
};
// 单例
private static ThreadPoolManage ourInstance = new ThreadPoolManage();
public static ThreadPoolManage getOurInstance(){
return ourInstance;
}
封装请求 [IHttpService ]
public interface IHttpService {
// 设置网址
void setUrl(String url);
// 设置请求参数
void setRequestData(byte[] requestData);
// 执行网络操作
void execute();
// 需要设置两个接口之间的关联
void setHttpCallBack(IHttpCallBack httpCallBack);
}
封装响应
public interface IHttpCallBack {
// 接受上一个接口的结果
// ----- 成功 -----
void onSuccess(InputStream inputStream);
// ----- 失败 -----
void onFailure();
}
各种任务顶层的类[HttpTask]
public class HttpTask<T> implements Runnable{
private IHttpService httpService;
private IHttpCallBack httpCallBack;
public<T> HttpTask(T requestInfo,String url,IHttpService httpService,IHttpCallBack httpCallBack){
this.httpService = httpService;
this.httpCallBack = httpCallBack;
httpService.setUrl(url);
// 上一个接口持有下一个接口的引用
httpService.setHttpCallBack(httpCallBack);
if (requestInfo != null) {
// 转换为字符串
String requsetContent = JSON.toJSONString(requestInfo);
try {
// 设置为请求参数 把参数转化为二进制
httpService.setRequestData(requsetContent.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
httpService.execute();
}
}
Service实现类 [JsonHttpService]
public class JsonHttpService implements IHttpService{
private String url;
private byte[] requestData;
IHttpCallBack httpCallBack;
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public void setRequestData(byte[] requestData) {
this.requestData = requestData;
}
@Override
public void setHttpCallBack(IHttpCallBack httpCallBack) {
this.httpCallBack = httpCallBack;
}
// 真正的网络操作在这里实现
@Override
public void execute() {
httpUrlConnPost();
}
HttpURLConnection urlConnection = null;
public void httpUrlConnPost(){
URL url = null;
try {
url = new URL(this.url);
urlConnection = (HttpURLConnection) url.openConnection();//打开httpl连接
urlConnection.setConnectTimeout(6000);//设置连接超时时间
urlConnection.setUseCaches(false);//不使用缓存
urlConnection.setInstanceFollowRedirects(true);//是成员函数 仅作用于当初前函数
urlConnection.setReadTimeout(3000);// 响应的超时时间
urlConnection.setDoInput(true);// 设置这个连接是否可以写入数据
urlConnection.setDoOutput(true);// 设置这个连接是否可以输出数据
urlConnection.setRequestMethod("POST");// 设置请求的方式
urlConnection.setRequestProperty("Content-Type","application/json;charset");
urlConnection.connect();//建立连接
// -------使用字节流发送数据-------
OutputStream out = urlConnection.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);//缓冲字节流包装字节
if (requestData != null) {
bos.write(requestData);
}
// 把这个字节数组的数据写入缓冲区中
bos.flush();//刷新缓冲区,发送数据
out.close();
bos.close();
// -------字符流写入数据--------
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
httpCallBack.onSuccess(in);
}
} catch (MalformedURLException e) {
e.printStackTrace();
httpCallBack.onFailure();
} catch (IOException e) {
e.printStackTrace();
}finally {
urlConnection.disconnect(); // 使用完关闭TCP连接,释放资源
}
}
}
CallBack实现类 [JsonHttpCallBack]
public class JsonHttpCallBack<M> implements IHttpCallBack {
// 相应对象的一个字节码
Class<M> responceClass;
// 回调数据
IDataCallBack<M> dataCallBack;
public JsonHttpCallBack(Class<M> responceClass, IDataCallBack<M> dataCallBack) {
this.responceClass = responceClass;
this.dataCallBack = dataCallBack;
}
// 用于切换线程
Handler handler = new Handler(Looper.getMainLooper());
@Override
public void onSuccess(InputStream inputStream) {
// 获取响应结果把byte数据转换成String数据
String content = getContent(inputStream);
// 请求结果 ---> Json字符串 ---> 对象
final M responce = JSON.parseObject(content, responceClass);
//线程切换
handler.post(new Runnable() {
@Override
public void run() {
// 把成功结果传输到调用层
if (dataCallBack != null) {
dataCallBack.OnSuccess(responce);
}
}
});
}
private String getContent(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Override
public void onFailure(final Exception e) {
// 线程切换
//把结果返回给调用层
handler.post(new Runnable() {
@Override
public void run() {
if (dataCallBack != null) {
dataCallBack.onFailure(e);
}
}
});
}
}
Volly
public class Volly {
public static<T,M> void sendJSONRequest(T requsetInfo,String url,Class<M> responce,IDataCallBack<M> dataCallBack){
IHttpService httpService = new JsonHttpService();
IHttpCallBack httpCallBack = new JsonHttpCallBack<>(responce,dataCallBack);
// 拼成任务
HttpTask<T> httpTask = new HttpTask<T>(requsetInfo,url,httpService,httpCallBack);
// 执行任务
ThreadPoolManage.getOurInstance().execute(httpTask);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private String url = "https://www.wanandroid.com/banner/json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
Volly.sendJSONRequest(null, url, BannerBean.class, new IDataCallBack<BannerBean>() {
@Override
public void OnSuccess(BannerBean dataBean) {
Log.i("OnSuccess", dataBean.getData().toString());
Toast.makeText(MainActivity.this, "这是什么:是"+dataBean.getData().get(0).getTitle(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Exception e) {
Log.i("--->", "onFailure"+e.toString());
}
});
}
}
看一下效果