1.提供网络请求的包装类
public RequestHolder<T>{
//T代表请求参数
private T requestInfo;
//url网络访问的地址
private String url;
//访问结果的接口回调
private IHttpListener httpListener;
//网络访问的具体实现
private IHttpService httpService;
//……略去RequestHolder属性值的get及set方法。
}
2.网络访问结果回调接口
public interface IHttpListener{
void onSuccess(HttpEntity httpEntity);
void onFail();
}
3.网络访问具体实现接口
//便于网络访问的扩展性 请求json数据、下载、上传
public interface IHttpSercice {
void setUrl(String url);
void excute();
void setRequestData(byte[] requestData);
void setHttpListener(IHttpListener httpListener);
}
4.供应用层回调的网络访问回调接口
public interface IDataListener<M>{
void onSuccess(M response);
void onFail();
}
5.网络访问的子线程HttpTask
public class HttpTask<T> implements Runnable{
private IHttpService httpService;
public HttpTask(RequestHold<T> requestHolder){
httpService = requestHolder.getHttpService();
httpService.setUrl(requestHolder.getUrl());
httpService.setHttpListener(requestHodler.getHttpListener());
T requset = requestHodler.getRequestInfo();
String requestInfo= JSON.toJSONString(request);
try {
httpService.setRequestData(requestInfo.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run(){
httpService.excute();
}
}
6.具体的JsonHttpService
public JsonHttpService implements IHttpService{
//网络请求返回
private class HttpResponseHandler extends BasicResponseHandler{
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException{
int code = response.getStatusLine().getStatusCode();
if(code==200){
httpListener.onSuccess(response.getEntity());
}else{
httpListener.onFail();
}
return null;
}
}
private HttpRespnceHandler httpRespnceHandler=new HttpRespnceHandler();
private IHttpListener httpListener;
private HttpClient httpClient=new DefaultHttpClient();
private HttpPost httpPost;
private String url;
private byte[] requestDate;
@Override
public void setUrl(String url) {
this.url=url;
}
@Override
public void setHttpListener(IHttpListener httpListener) {
this.httpListener=httpListener;
}
@Override
public void setRequestData(byte[] requestData) {
this.requestDate=requestData;
}
@Override
public void excute() {
httpPost=new HttpPost(url);
ByteArrayEntity byteArrayEntity=new ByteArrayEntity(requestDate);
httpPost.setEntity(byteArrayEntity);
try {
httpClient.execute(httpPost,httpRespnceHandler);
} catch (IOException e) {
httpListener.onFail();
}
}
}
7.JsonDataListener调用层回调接口
public class JsonDealListener<M> implements IHttpListener{
private Class<M> response;
private IDataListener<M> dataListener;
Handler handler = new Handler(Looper.getMainLooper());
public JsonDealLitener(Class<M> responese, IDataListener<M> dataListener) {
this.responese = responese;
this.dataListener = dataListener;
}
@Override
public void onFail() {
dataListener.onFail();
}
@Override
public void onSuccess(HttpEntity httpEntity) {
InputStream inputStream=null;
try {
inputStream=httpEntity.getContent();
String content=getContent(inputStream);
final M m= JSON.parseObject(content,responese);
handler.post(new Runnable() {
@Override
public void run() {
dataListener.onSuccess(m);
}
});
} catch (IOException e) {
dataListener.onFail();
}
}
private String getContent(InputStream inputStream) {
String content=null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//StringBuilder非线程安全StringBuffer线程安全
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
dataListener.onFail();
System.out.println("Error=" + e.toString());
} finally {
try {
inputStream.close();
} catch (IOException e) {
System.out.println("Error=" + e.toString());
}
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
dataListener.onFail();
}
return content;
}
}
8.Volley调用
public class Volley{
public static <T,M> void sendRequest(T requestInfo,String url,
Class<M> response,IDataListener dataListener){
RequestHodler<T> requestHodler=new RequestHodler<>();
requestHodler.setUrl(url);
IHttpService httpService=new JsonHttpService();
IHttpListener httpListener=new JsonDealLitener<>(response,dataListener);
requestHodler.setHttpService(httpService);
requestHodler.setHttpListener(httpListener);
HttpTask<T> httpTask=new HttpTask<>(requestHodler);
try {
ThreadPoolManager.getInstance().execte(new FutureTask<Object>(httpTask,null));
} catch (InterruptedException e) {
dataListener.onFail();
}
}
}
9.线程池管理
public class ThreadPoolManager{
private static ThreadPoolManager instance=new ThreadPoolManager();
private LinkedBlockingQueue<Future<?>> taskQuene=new LinkedBlockingQueue<>();
private ThreadPoolExecutor threadPoolExecutor;
private RejectedExecutionHandler handler=new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
taskQuene.put(new FutureTask<Object>(r,null) {});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public static ThreadPoolManager getInstance() {
return instance;
}
private ThreadPoolManager(){
threadPoolExecutor=new ThreadPoolExecutor(4,10,10, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(4), handler);
threadPoolExecutor.execute(runable);
}
private Runnable runable =new Runnable() {
@Override
public void run() {
while (true){
FutureTask futrueTask=null;
try {
futrueTask= (FutureTask) taskQuene.take();
}catch (InterruptedException e) {
e.printStackTrace();
}
if(futrueTask!=null){
threadPoolExecutor.execute(futrueTask);
}
}
}
}
public <T> void execte(FutureTask<T> futureTask) throws InterruptedException {
taskQuene.put(futureTask);
}
}
10.客户端调用
User user=new User();
user.setName("13343491234");
user.setPassword("123456");
Volley.sendRequest(user, url, LoginRespense.class, new IDataListener<LoginRespense>() {
@Override
public void onSuccess(LoginRespense loginRespense) {
Log.i(TAG,loginRespense.toString());
}
@Override
public void onFail() {
Log.i(TAG,"获取失败");
}
});
请求数据包装成RequestHold 任务是一个线程,任务的管理交给线程池去管理,具体的任务请求交给Service。
网友评论