工作几年发现自己没留下啥东西,天天开发开发,没总结过。 这次想总结下。故而写这个系列的博客。希望对广大的开发者有所帮助。
OK 首先先分析下 框架的作用,以及框架所应拥有的功能
框架有啥好处那,你只要写了一次以后就可以重复利用了。
无非是拷贝过来拷贝过去。写的框架必须简单易懂。
功能以及分模块:
1. 联网 模块
2. 数据缓存模块。(缓存这里比较重要,因为每次不肯能都去获取新数据,太费流量了。)
3. 图片联网获取并加载模块。以及图片的缓存
4. 数据库模块
ok 废话不多说 上点干货。下面是框架的结构图
需要一个jar包 httpmime.jar
由于Android附带的HttpClient版本暂不支持多部件POST请求,所以我们需要用到一个HttpMime开源项目,该组件是专门处理与MIME类型有关的操作。因为HttpMime是包含在HttpComponents 项目中的,所以我们需要去apache官方网站下载HttpComponents,然后把其中的HttpMime.jar包放到项目中去
先写个联网框架:httpmanager- 这个只是用来联网的
package com.example.net.manager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import com.example.net.BaseApplication;
import com.example.net.Interface.IDownloadListener;
import com.example.net.utils.LogUtil;
import com.example.net.utils.NetWorkUtil;
import android.net.http.AndroidHttpClient;
/**
* HttpManager 最基本的联网请求 只做最基本的联网操作
*
* @author liuml
*
* 2015-3-12 下午3:14:27
*/
public class HttpManager {
private static final String TAG = "HttpManager";
public static HttpClient getDefaultHttpClient() {
//xxxxx 输入自己的项目名字
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("xxxxx");
// HttpClient httpClient = new DefaultHttpClient();
return httpClient;
}
/**
* 不带参数的get请求
*
* @param url
* @param listener
* @return
*/
public static String requestJsonWithGet(String url, IDownloadListener listener) {
// 判断网路状态
if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
if (listener != null) {
listener.onNetworkDisconnect();
}
return null;
}
String requestResult = null;
HttpClient httpClient = getDefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
LogUtil.d(TAG, "url = " + url);
try {
HttpResponse response = httpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
LogUtil.d(TAG, "服务器返回码" + statusCode);
if (HttpStatus.SC_OK == statusCode) {
HttpEntity entity = response.getEntity();
if (entity != null) {
requestResult = EntityUtils.toString(entity);
if (listener != null) {
listener.onDownloadSuccessed(requestResult);
}
} else {
if (listener != null) {
listener.onDownloadFailed();
}
}
} else {
if (listener != null) {
listener.onDownloadFailed();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
listener.onDownloadFailed();
} catch (IOException e) {
e.printStackTrace();
listener.onDownloadFailed();
} finally {
if (httpClient instanceof AndroidHttpClient) {
((AndroidHttpClient) httpClient).close();
}
}
return requestResult;
}
/**
* 带参数的get请求
*
* @param url
* @param getParameters
* @param listener
* @return
*/
public static String requestJsonWithGet(String url, List<NameValuePair> parameters, IDownloadListener listener) {
if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
if (listener != null) {
listener.onNetworkDisconnect();
}
return null;
}
String murl = url + "?" + NameValuePair2String(parameters);
LogUtil.d(TAG, "带参数的Get请求(从网络)= " + murl);
String requestResult = null;
HttpClient httpClient = getDefaultHttpClient();
HttpGet httpRequest = new HttpGet(murl);
try {
HttpResponse response = httpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
HttpEntity entity = response.getEntity();
if (entity != null) {
requestResult = EntityUtils.toString(entity);
if (listener != null) {
listener.onDownloadSuccessed(requestResult);
}
} else {
if (listener != null) {
listener.onDownloadFailed();
}
}
} else {
if (listener != null) {
listener.onDownloadFailed();
}
}
} catch (ClientProtocolException e) {
if (listener != null) {
listener.onDownloadFailed();
}
e.printStackTrace();
} catch (IOException e) {
if (listener != null) {
listener.onDownloadFailed();
}
e.printStackTrace();
} finally {
if (httpClient instanceof AndroidHttpClient) {
((AndroidHttpClient) httpClient).close();
}
}
return requestResult;
}
/**
* 带参数的Post请求
*
* @param url
* @param postParameters
* @param listener
* @return
*/
public static String requestJsonWithPost(String url, List<NameValuePair> postParameters, IDownloadListener listener) {
LogUtil.d(TAG, "requestJsonWithPost");
if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
if (listener != null) {
listener.onNetworkDisconnect();
}
return null;
}
String requestResult = null;
HttpPost httpRequest = new HttpPost(url);
if (postParameters != null && postParameters.size() > 0) {
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(postParameters, "utf-8");
httpRequest.setEntity(entity);
} catch (UnsupportedEncodingException e) {
if (listener != null) {
LogUtil.d(TAG, "UserLogin UnsupportedEncodingException, e = " + e);
listener.onDownloadFailed();
}
return null;
}
}
BasicHttpParams params = new BasicHttpParams();
params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
HttpClient httpClient = new DefaultHttpClient(params);
HttpResponse response = null;
try {
response = httpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
HttpEntity entity = response.getEntity();
requestResult = EntityUtils.toString(entity);
if (listener != null) {
LogUtil.d(TAG, "UserLogin onDownloadSuccessed");
listener.onDownloadSuccessed(requestResult);
}
} else {
if (listener != null) {
LogUtil.d(TAG, "UserLogin HttpStatus.SC_OK != statusCode");
LogUtil.d(TAG, "状态码 = " + statusCode);
listener.onDownloadFailed();
}
}
} catch (Exception e) {
if (listener != null) {
LogUtil.d(TAG, "UserLogin HttpStatus.SC_OK != statusCode");
listener.onDownloadFailed();
}
e.printStackTrace();
} finally {
if (httpClient instanceof AndroidHttpClient) {
((AndroidHttpClient) httpClient).close();
}
}
return requestResult;
}
/**
* 参数转化
*
* @param parameters
* @return
*/
private static String NameValuePair2String(List<NameValuePair> parameters) {
StringBuilder builder = new StringBuilder();
for (NameValuePair item : parameters) {
builder.append(item.getName());
builder.append("=");
builder.append(item.getValue());
builder.append("&");
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
}
然后我创建一个json管理器 jsonmanager
jsonManager主要的功能有:
- 创建线程池,处理联网请求,异步加载。
- 判断网络状态,以及 调用存储json数据的方法。
- 。。反正就是一系列判断。
package cn.com.psy.xinhaijiaoyu.mamager;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.NameValuePair;
import android.content.Context;
import cn.com.psy.xinhaijiaoyu.XinHaiApplication;
import cn.com.psy.xinhaijiaoyu.Interface.IDownloadListener;
import cn.com.psy.xinhaijiaoyu.cache.JsonCacheManager;
import cn.com.psy.xinhaijiaoyu.util.LogUtil;
import cn.com.psy.xinhaijiaoyu.util.NetWorkUtil;
/**
* json 数据管理
*
* @author liuml 2014-2-27
*
*/
public class JsonManager {
private static final String TAG = "JsonManager";
private JsonCacheManager mJsonCacheManager;
private ExecutorService mExecutorService;
private static final int THREAD_POOL_SIZE = 5;
public JsonManager(Context context) {
mJsonCacheManager = new JsonCacheManager(context);
mExecutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
/**
* 没有参数的get请求
*
* @param url
* @param listener
*/
public void loadJsonByGet(String url, IDownloadListener listener) {
loadJsonByGet(url, listener, false);
}
/**
* 有参数的get请求,无服务器判断
*
* @param url
* @param parameters
* @param listener
*/
public void loadJsonByGet(final String url, final List<NameValuePair> parameters, final IDownloadListener listener) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByHttpGet(url, parameters, listener);
}
});
}
/**
* 有参数的get请求 有服务器判断
*
* @param url
* @param parameters
* @param listener
* @param fromServer
*/
public void loadJsonByGet(final String url, final List<NameValuePair> parameters, final IDownloadListener listener, final Boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByJsonGet(url, parameters, listener, fromServer);
}
});
}
public void loadJsonByGet(final String url, final List<NameValuePair> parameters, final IDownloadListener listener, final Boolean fromServer, final long timeout) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByJsonGet(url, parameters, listener, fromServer, timeout);
}
});
}
/**
* 获取数据get请求
*
* @param url
* @param parameters
* @param listener
*/
protected void loadJsonByHttpGet(String url, List<NameValuePair> parameters, IDownloadListener listener) {
String json = null;
json = loadJsonFromServerByHttpGet(url, parameters, listener);
LogUtil.d(TAG, "loadJsonByHttpGet==" + json);
}
/**
* 没有参数的get请求
*
* @param url
* @param listener
* @param fromServer
*/
public void loadJsonByGet(final String url, final IDownloadListener listener, final boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByHttpGet(url, listener, fromServer);
}
});
}
/**
* 无参数的post请求
*
* @param url
* @param listener
* @param fromServer
*/
public void loadJsonByPost(final String url, final IDownloadListener listener, final boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByHttpPost(url, listener, fromServer);
}
});
}
public void loadJsonByHttpGet(String url, IDownloadListener listener, boolean fromServer) {
String json = null;
if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
json = getJsonFromCacheFile(url);
if (json != null) {
if (listener != null) {
listener.onDownloadSuccessed(json);
}
return;
}
}
json = loadJsonFromServerByHttpGet(url, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(url, json);
}
}
public void loadJsonByHttpPost(String url, IDownloadListener listener, boolean fromServer) {
String json = null;
if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
json = getJsonFromCacheFile(url);
if (json != null) {
if (listener != null) {
listener.onDownloadSuccessed(json);
}
return;
}
}
json = loadJsonFromServerByHttpPost(url, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(url, json);
}
}
private String loadJsonFromServerByHttpGet(String url, IDownloadListener listener) {
return HttpManager.requestJsonWithGet(url, listener);
}
private String loadJsonFromServerByHttpGet(String url, List<NameValuePair> parameters, IDownloadListener listener) {
return HttpManager.requestJsonWithGet(url, parameters, listener);
}
private String loadJsonFromServerByHttpPost(String url, IDownloadListener listener) {
return HttpManager.requestJsonWithPost(url, listener);
}
/**
* 有参数的post请求
* @param url
* @param parameters
* @param listener
*/
public void loadJsonByPost(String url, List<NameValuePair> parameters, IDownloadListener listener) {
loadJsonByPost(url, parameters, listener, false);
}
public void loadJsonByPost(final String url, final List<NameValuePair> parameters, final IDownloadListener listener, final boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
loadJsonByHttpPost(url, parameters, listener);
}
});
}
// 直接访问网络
public void loadJsonByHttpPost(String url, List<NameValuePair> parameters, IDownloadListener listener) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
String json = null;
String urlParams = url + "?" + NameValuePair2String(parameters);
LogUtil.d(TAG, "post请求 url = " + urlParams);
json = loadJsonFromServerByHttpPost(url, parameters, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(urlParams, json);
}
}
private String loadJsonFromServerByHttpPost(String url, List<NameValuePair> parameters, IDownloadListener listener) {
return HttpManager.requestJsonWithPost(url, parameters, listener);
}
private String getJsonFromCacheFile(String url) {
return mJsonCacheManager.getJsonFromDiskCache(url);
}
private String getJsonFromCacheFile(String url, long timeout) {
return mJsonCacheManager.getJsonFromDiskCache(url, timeout);
}
private String NameValuePair2String(List<NameValuePair> parameters) {
StringBuilder builder = new StringBuilder();
for (NameValuePair item : parameters) {
builder.append(item.getName());
builder.append("=");
builder.append(item.getValue());
builder.append("&");
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/**
* 上传图片
*
* @param url
* @param parameters
* @param avartarFile
* @param listener
*/
public void uploadUserAvartar(final String url, final List<NameValuePair> parameters, final File avartarFile, final IDownloadListener listener) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
uploadUserAvartarByPost(url, parameters, avartarFile, listener);
}
});
}
protected void uploadUserAvartarByPost(String url, List<NameValuePair> parameters, File avartarFile, IDownloadListener listener) {
HttpManager.uploadUserAvartar(url, parameters, avartarFile, listener);
}
public void uploadMultiPics(final String url, final List<NameValuePair> parameters, final List<String> picsList, final IDownloadListener listener, final boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
mExecutorService.execute(new Runnable() {
@Override
public void run() {
uploadMultiPicsByPost(url, parameters, picsList, listener);
}
});
}
protected void uploadMultiPicsByPost(String url, List<NameValuePair> parameters, List<String> picsList, IDownloadListener listener) {
HttpManager.uploadMultiPics(url, parameters, picsList, listener);
}
public void loadJsonByJsonPost(String url, List<NameValuePair> parameters, IDownloadListener listener, boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
String json = null;
String urlParams = url + NameValuePair2String(parameters);
LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
json = getJsonFromCacheFile(urlParams);
LogUtil.d(TAG, "从cache 中 json " + json);
if (json != null) {
if (listener != null) {
listener.onDownloadSuccessed(json);
}
return;
}
}
json = loadJsonFromServerByHttpPost(url, parameters, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(urlParams, json);
}
}
public void loadJsonByJsonGet(String url, List<NameValuePair> parameters, IDownloadListener listener, boolean fromServer) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
String json = null;
String urlParams = url + NameValuePair2String(parameters);
LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
json = getJsonFromCacheFile(urlParams);
LogUtil.d(TAG, "从cache 中 json " + json);
if (json != null) {
if (listener != null) {
listener.onDownloadSuccessed(json);
}
return;
}
}
json = loadJsonFromServerByHttpGet(url, parameters, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(urlParams, json);
}
}
public void loadJsonByJsonGet(String url, List<NameValuePair> parameters, IDownloadListener listener, boolean fromServer, long timeout) {
if (url == null) {
if (listener != null) {
listener.onDownloadFailed();
}
return;
}
String json = null;
String urlParams = url + NameValuePair2String(parameters);
LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
json = getJsonFromCacheFile(urlParams, timeout);
LogUtil.d(TAG, "从cache 中 json " + json);
if (json != null) {
if (listener != null) {
listener.onDownloadSuccessed(json);
}
return;
}
}
json = loadJsonFromServerByHttpGet(url, parameters, listener);
if (json != null) {
mJsonCacheManager.addJsonToDiskCache(urlParams, json);
}
}
}
这是json管理器。 在哪里调用他呢?
这时候我写个类DataManager 在这里调用他
package com.example.net.manager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.net.Interface.IDownloadListener;
import com.example.net.config.ApiHttpConfig;
import com.example.net.config.MyParameters;
import com.example.net.utils.LogUtil;
/**
* 数据管理
*
* @author liuml 2014-2-27
*
*/
public class DataManager {
private static final String TAG = "DataManager";
// private static DataManager mInstance;
private JsonManager mJsonManager;
public DataManager(JsonManager jsonManager) {
mJsonManager = jsonManager;
}
/**
* 登陆接口
*
* @param username
* 用户名
* @param passwd
* 密码
* @param imsi
* 手机imsi
* @param listener
* 回调接口
* @param formServer
* 是否从服务器上获取(默认为false 如果本地没有数据则从网上获取, 如果为true 则强制从网上获取)
*/
public void login(String username, String passwd, String imsi, IDownloadListener listener, boolean formServer) {
String url = ApiHttpConfig.getInstance().loginApi();
LogUtil.d(TAG, "login url ========================== " + url);
List<NameValuePair> parameters = MyParameters.getInstance().loginParameters(username, passwd, imsi);
mJsonManager.loadJsonByPost(url, parameters, listener, formServer);
}
}
这里我也只是做个登陆接口。其他接口想怎么写就怎么写
对了 还有参数的添加。添加的话需要再写一个类。
package com.example.net.config;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.net.utils.LogUtil;
public class MyParameters extends ApiHttpConfig{
private static MyParameters Parameters = new MyParameters();
public static MyParameters getInstance() {
return Parameters;
}
/**
* 登陆参数
* @param username
* @param passwd
* @param imsi
* @return
*/
public List<NameValuePair> loginParameters(String username, String passwd, String imsi) {
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
if (username == null) {
username = "";
}
if (passwd == null) {
passwd = "";
}
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", passwd));
parameters.add(new BasicNameValuePair("imsi", imsi));
LogUtil.d(TAG + "loginParameters :", parameters.toString());
return parameters;
}
}
这个类继承ApiHttpConfig 这个类是用作保存接口的地方
package com.example.net.config;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.net.utils.LogUtil;
/**
*
* @author liuml
*
* 2015-4-22 上午11:58:11
*/
public class ApiHttpConfig {
private static ApiHttpConfig apiConfig = new ApiHttpConfig();
public static final String DefaultParserUrl = "http://192.168.1.1/api/mapi";
// 登录
public static final String LOGIN_PART_STRING = "/Login";
public static final String PARENT_AND_CHILD_REGIST = "/ParentRegist";
protected static final String TAG = "ApiHttpConfig";
public static ApiHttpConfig getInstance() {
return apiConfig;
}
public String loginApi() {
return DefaultParserUrl + LOGIN_PART_STRING;
}
}
今天就暂时写这么多吧。。ok
里面还有些缓存模块的东西 我明天再加上去吧。。等我全部写完了在吧框架代码发上去
时间: 2024-11-06 20:49:14