框架起始篇...意义重大,影响深远....
适用场景,为了便于秒速我们定义网络请求的对象为Action,UI层调起Action发起网络请求,Action处理请求响应的结果,并通知UI层令其得到Action处理后的数据。
1、定义网络请求监听
public interface HttpListener {
/**
* 完成网络请求
* @param response
*/
public void onComplete(String response);
/**
* 网络请求失败
*/
public void onError();
}
2、定义HTTP工具
主要用到request方法
/**
* HTTP工具类
* @author: linxcool.hu
*/
public class HttpUtil {
private Context context;
/**HTTP常量-GET请求*/
public static final int HTTP_METHOD_GET=1;
/**HTTP常量-POST请求*/
public static final int HTTP_METHOD_POST=2;
/**HTTP常量-请求限制时间*/
public static final int HTTP_REQ_LIMIT_TIME=15*1000;
/**HTTP常量-响应限制时间*/
public static final int HTTP_RES_LIMIT_TIME=25*1000;
//返回码
public static final int RES_CODE_SUCCESS=200;
public static final int RES_CODE_ERROR=1;
public static final int RES_CODE_FAIL=2;
private HttpClient client;
private HttpResponse response;
public HttpUtil(Context context) {
this.context=context;
}
public HttpClient createHttpClient(){
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_REQ_LIMIT_TIME);
HttpConnectionParams.setSoTimeout(params,HTTP_RES_LIMIT_TIME);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
return new DefaultHttpClient(params);
}
public HttpUriRequest createHttpRequest(String url,int method){
HttpUriRequest request=null;
if(method == HTTP_METHOD_GET){
request=new HttpGet(url);
}else{
request=new HttpPost(url);
}
//关闭 100-Continue 询问
request.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
return request;
}
public boolean openUrl(HttpUriRequest request){
client=createHttpClient();
try {
response=client.execute(request);
return true;
} catch (IOException e) {
e.printStackTrace();
response=null;
}
return false;
}
public String getHttpResponse(){
String result = null;
try {
if(response==null)return null;
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1)
content.write(sBuffer, 0, readBytes);
result = new String(content.toByteArray());
result=URLDecoder.decode(result, "UTF-8");
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(client!=null)
client.getConnectionManager().shutdown();
}
return result;
}
public void request(
final String url,final HttpUriRequest request,final HttpListener listerner) {
new Thread() {
@Override
public void run() {
boolean ret = openUrl(request);
if(!ret){
listerner.onError();
return;
}
listerner.onComplete(getHttpResponse());
}
}.start();
}
}
3、定义网络请求动作Action
每个网络请求动作都继承以下类
/**
* 基础动作类
* @author: linxcool.hu
*/
public abstract class BaseAction extends Observable implements HttpListener,Runnable{
private static final String TAG="BaseAction";
//动作ID列表 根据实际情况更改
public static final int ACTION_ID_INTRO=1;
public static final int ACTION_ID_SHARE=2;
//响应状态结果
public static final int SUCCESS=0;
public static final int ERROR=1;
public static final int EXCEPTION=2;
//上下文对象
protected Context context;
protected ActionService actionService;
//动作信息列表
protected int actionId;
protected HttpUtil httpUtil;
protected int method;
protected String content;
//响应信息
protected String response;
protected String resMsg;
public String getResMsg() {
return resMsg;
}
public BaseAction(ActionService actionService,int actionId){
this.actionService=actionService;
this.context=actionService.getActivity();
this.actionId=actionId;
httpUtil=new HttpUtil(context);
method=HttpUtil.HTTP_METHOD_POST;
}
/**
* 执行网络请求动作
*/
public void actionStart(){
try {
doRequest(
httpUtil.REQUEST_HOST+getURL(),
content);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
protected void putBasicData(JSONObject jsonObj) throws JSONException{
}
public abstract void putData(Object... datas);
public void doRequest(String url,String content) throws UnsupportedEncodingException{
HttpUriRequest request=httpUtil.createHttpRequest(url, method);
if(content != null){
HttpPost post=(HttpPost) request;
post.setEntity(new StringEntity(content));
}
httpUtil.request(url, request, this);
}
@Override
public void onComplete(String response) {
this.response=response;
((Activity)context).runOnUiThread(this);
}
@Override
public void onError() {
response=null;
((Activity)context).runOnUiThread(this);
}
private String getURL(){
switch (actionId) {
case ACTION_ID_INTRO:
return "login";
}
}
@Override
public void run() {
setChanged();
if(response==null){
notifyObservers(ERROR);
return;
}
try {
JSONObject obj = new JSONObject(response);
int code=obj.getInt("code");
if(code==HttpUtil.RES_CODE_SUCCESS){
onResSuccess(obj);
notifyObservers(SUCCESS);
}else{
resMsg=obj.getString("msg");
notifyObservers(EXCEPTION);
}
} catch (Exception e) {
e.printStackTrace();
resMsg="数据解析错误";
notifyObservers(ERROR);
}
}
/**
* 网络请求成功后将执行该方法
* @param obj
* @throws Exception
*/
public abstract void onResSuccess(JSONObject obj) throws Exception;
}
4、动作服务类根据ActionId获取对应Action
/**
* 动作服务对象
* @author: linxcool.hu
*/
public class ActionService {
private Activity activity;
public ActionService(Activity activity){
this.activity=activity;
}
/**
* 根据动作ID获取动作对象
* @param actionId
* @return
*/
public BaseAction getAction(int actionId){
switch (actionId) {
case BaseAction.ACTION_ID_INTRO:
return new IntroAction(this);
case BaseAction.ACTION_ID_SHARE:
return new ShareAction(this);
}
return null;
}
/**
* 获取Context对象
* @return
*/
public Activity getActivity() {
return activity;
}
}
5、在UI视图上实现Observer接口,并将该视图添加到对应的Action观察者队列中,在Update方法中处理界面逻辑
@Override
public void update(Observable observable, Object data) {
int code=(Integer) data;
switch (code) {
case BaseAction.SUCCESS:
break;
case BaseAction.EXCEPTION:
break;
case BaseAction.ERROR:
break;
}
}