1.网络请求框架
image.png实现
1.线程管理类 单例实现
public class ThreadManager {
//单例
private static ThreadManager threadManager = new ThreadManager();
public static ThreadManager getInstance(){
return threadManager;
}
//定义请求队列 阻塞 LinkedBlockingQueue是一个单向链表实现的阻塞队列。该队列按 FIFO(先进先出)
private LinkedBlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<>();
//添加队列
public void addTask(Runnable runnable) {
if (runnable == null) {
return;
}
mQueue.add(runnable);
}
//处理中心 线程池
private ThreadPoolExecutor threadPoolExecutor;
public ThreadManager() {
threadPoolExecutor = new ThreadPoolExecutor(3, 10, 10, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// 拒绝的线程从新添加到 队列中
mQueue.add(r);
}
});
threadPoolExecutor.execute(runnable);
}
//核心线程
private Runnable runnable = new Runnable() {
@Override
public void run() {
//死循环
while (true) {
try {
// 如果队列里没有 就会阻塞 有了 继续执行
Runnable take = mQueue.take();
threadPoolExecutor.execute(take);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
2.请求的接口
public interface IHttpRequest {
//请求地址
void setUrl(String url);
//请求参数
void setParam(byte[] param);
//执行
void execute();
//关联结果
void setListener(IHttpListener listener);
}
3.请求的返回接口
public interface IHttpListener {
void onSuccess(InputStream inputStream);
void onFailure();
}
4.请求的数据返回接口
/**
* 给用户的
* @param <T>
*/
public interface IDataListener<T> {
void onSuccess(T t);
void onFailure();
}
5.请求的实现
public class JsonHttpRequest implements IHttpRequest {
private String url;
private byte[] params;
private IHttpListener iHttpListener;
private HttpURLConnection connection;
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public void setParam(byte[] param) {
this.params = param;
}
@Override
public void setListener(IHttpListener listener) {
this.iHttpListener = listener;
}
@Override
public void execute() {
URL url = null;
try {
url=new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);//允许输出流,即允许上传
connection.setDoInput(true);//允许输入流,即允许下载
connection.setUseCaches(false);//不使用缓冲
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(30000); // 设置连接超时时间
connection.setReadTimeout(30000); // 设置读取超时时间
connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
connection.connect();
OutputStream outputStream= connection.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
bufferedOutputStream.write(params);
bufferedOutputStream.flush();
outputStream.close();
bufferedOutputStream.close();
if (connection.getResponseCode() == connection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
iHttpListener.onSuccess(inputStream);
}else {
throw new RuntimeException("请求失败");
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("请求失败");
}finally {
connection.disconnect();
}
}
}
6.请求结果的实现
public class JsonHttpListener<T> implements IHttpListener {
private Class<T> responce;
private IDataListener iDataListener;
//主线程
private Handler handler = new Handler(Looper.getMainLooper());
public JsonHttpListener(Class<T> responce, IDataListener iDataListener) {
this.responce = responce;
this.iDataListener = iDataListener;
}
@Override
public void onSuccess(InputStream inputStream) {
String content = null;
try {
content = getContent(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
final T t = JSON.parseObject(content, responce);
handler.post(new Runnable() {
@Override
public void run() {
iDataListener.onSuccess(t);
}
});
}
/**
* inputstream 转换为string
*
* @param inputStream
* @return
*/
private String getContent(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String tmp = null;
StringBuffer content = new StringBuffer();
while ((tmp = bufferedReader.readLine()) != null) {
content.append(tmp);
}
return content.toString();
}
@Override
public void onFailure() {
}
}
7.请求队列
public class HttpTask<T> implements Runnable {
private IHttpListener httpListener;
private IHttpRequest httpRequest;
public HttpTask(IHttpListener httpListener, IHttpRequest httpRequest,String url,T requestData) {
this.httpListener = httpListener;
this.httpRequest = httpRequest;
this.httpRequest.setUrl(url);
this.httpRequest.setListener(httpListener);
//对象转为字节
if (requestData != null) {
String s = JSON.toJSONString(requestData);
try {
this.httpRequest.setParam(s.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
this.httpRequest.execute();
}
}
8.请求
public class JettNetFramework {
/**
* 请求
* @param url
* @param params
* @param responce
* @param listener
* @param <T>
* @param <M>
*/
public static<T,M> void sendUserRequest(String url,T params,Class<M> responce,IDataListener listener){
IHttpRequest httpRequest = new JsonHttpRequest();
IHttpListener httpListener = new JsonHttpListener<>(responce,listener);
HttpTask<T> task = new HttpTask<>(httpListener,httpRequest,url,params);
ThreadManager.getInstance().addTask(task);
}
}
9.调用入口
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = null;
RequestBean requestBean = new RequestBean();
JettNetFramework.sendUserRequest(url,requestBean,ResponceBean.class, new IDataListener<ResponceBean>() {
@Override
public void onSuccess(ResponceBean responceBean) {
}
@Override
public void onFailure() {
}
});
}
网友评论