从零开始写Http框架---第二篇
2016-03-15 21:48
609 查看
本篇概述:
使用线程池ExecutorService来管理线程, 具体Executor相关原理可以参考《Think in java》这本书
改动后代码:
/*** 网络请求入口
* */
public class HttpUtil { public static void get(String rootUrl, RequestParams params, final LincolnCallBack<JSONObject> callBack) { rootUrl = UrlUtil.dealGetParams(rootUrl, params); TaskController taskController = TaskController.registrInstance(); taskController.start(rootUrl,HttpMethod.GET, params, callBack); } }
/**
* 线程控制类
*/
public class TaskController { private static TaskController taskController; private static ExecutorService executor; private static int MAX_THREAD_COUNT= 10; public static TaskController registrInstance(){ if (taskController == null) { synchronized (TaskController.class) { if (taskController == null) { taskController = new TaskController(); executor = Executors.newFixedThreadPool(MAX_THREAD_COUNT); } } } return taskController; } public <T> void start(String rootUrl,HttpMethod method ,RequestParams params,LincolnCallBack<JSONObject> callback){ HttpTask task = new HttpTask(rootUrl,method, callback); executor.submit(task); } }
任务线程类
public class HttpTask implements Runnable{ private String rootUrl; private LincolnCallBack callBack; private HttpMethod method; public HttpTask(String rootUrl,HttpMethod method,LincolnCallBack callback){ this.rootUrl = rootUrl; this.callBack = callback; this.method = method; } public void sendRequest(){ try { URL url = new URL(rootUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method.toString()); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); ByteArrayOutputStream byteOutSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = -1; while ((length = inputStream.read(buffer)) != -1) { byteOutSteam.write(buffer, 0, length); } String resultString = byteOutSteam.toString(); JSONObject object = new JSONObject(resultString); callBack.onSuccess(null, object); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { sendRequest(); } }
源代码下载
相关文章推荐
- springMVC No mapping found for HTTP request with URI
- 使用okhttp报错"Missing type parameter"
- java SE基础(TCP Socket通信)
- http和https的差别
- TCP的流量控制
- python之网络爬虫
- java SE基础(URL访问网络资源)
- HTTP 单线程 模拟迅雷下载
- TCP/IP协议三次握手与四次握手流程解析
- 手写服务器httpserver_准备_Socket入门_htmlJAVA195-196
- TCP和Http的区别!我都搞懂了,你就别迷糊了!
- Okhttp
- android 网络实时监听网络状态变化 及 网络类型判断
- HTTP、TCP、UDP、Socket
- 新博客(http://www.cnblogs.com/shentr/)
- 发布b3log-solo后,访问http://localhost:8080/b3log-solo/提示错误为staticServePath Error。
- [网络流24题][CODEVS1922]骑士共存问题(最大流)
- HTTP协议是做什么的
- BZOJ_P3345 PKU2914 Minimum Cut(网络流最小割)
- Android网络开发之HttpURLConnection