json数据保存在本地有2中思路:,第一种是直接保存在file中,第二种是每一条保存在数据库中。第一种更好实现一些,通过使用FileWriter往文件中写数据,写数据的时候路径很关键,关于路径有2个思路,当sd卡可用的时候保存在sd卡中,sd卡不可用的时候保存在应用的cache目录中。其中需要注意的是,在写文件数据之前,第一行写了一个时间按,是数据的过期时间,数据过期了就没有必须要使用缓存数据。
HomeProtocal.java往文件中写数据,保存在文件中,利用BufferedWriter来实现
package com.ldw.market.protocol;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import com.ldw.market.http.HttpHelper;
import com.ldw.market.http.HttpHelper.HttpResult;
import com.ldw.market.utils.FileUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.IOUtils;
public class HomeProtocal {
//请求服务器数据,参数index,可以分批加载
public void load(int index){
//从本地请求数据
String json = loadLocal(index);
//返回的数据是json
if(json == null){
json = loadServer(index);
//保存到本地
if(json != null){
saveLocal(json, index);
}
}
//json不为空,就解析json
if(json != null){
parseJson(json);
}
}
//解析json数据
private void parseJson(String json) {
// TODO Auto-generated method stub
}
//将json保存在本地:方法1把整个json文件写到一个本地文件中,方法2吧每条数据都摘出来保存在数据库中
private void saveLocal(String json, int index) {
//创建一个buffer
BufferedWriter bw = null;
try {
File dir=FileUtils.getCacheDir();
//创建一个文件
File file = new File(dir, "home_" + index); // /mnt/sdcard/market/cache/home_0
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
//在第一行写一个过期时间
bw.write(System.currentTimeMillis() + 1000 * 100 + "");
bw.newLine();// 换行
bw.write(json);// 把整个json文件保存起来
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(bw);
}
}
//从服务器请求json数据
private String loadServer(int index) {
//请求地址http://127.0.0.1:8090/home?index=1
HttpResult httpResult = HttpHelper.get(HttpHelper.URL +"home"
+ "?index=" + index);
//得到结果
String json = httpResult.getString();
System.out.println(json);
return json;
}
//加载本地保存的数据
private String loadLocal(int index) {
// 如果发现时间过期了,就不用本地的缓存
return null;
}
}
创建文件夹来保存缓存文件FileUtils.java
package com.ldw.market.utils;
import java.io.File;
import android.os.Environment;
/*
* 管理所需要的文件夹
*/
public class FileUtils {
public static final String CACHE = "cache";// 缓存的json
public static final String ICON = "icon";// 缓存的图片
public static final String ROOT = "market";// 根路径
/*
* 获取图片的缓存的路径
*/
public static File getIconDir() {
return getDir(ICON);
}
/*
* 获取缓存路径
*/
public static File getCacheDir() {
return getDir(CACHE);
}
public static File getDir(String cache) {
// 使用StringBuilder
StringBuilder path = new StringBuilder();
//sd卡可用
if (isSDAvailable()) {
// 获取到sd卡的目录添加到path
path.append(Environment.getExternalStorageDirectory().getAbsolutePath());
path.append(File.separator);// 加上斜线'/'
path.append(ROOT);// 加上ROOT作为路径/mnt/sdcard/market
path.append(File.separator);// 加斜线
path.append(cache);// /mnt/sdcard/market/cache
}else{
File filesDir = UiUtils.getContext().getCacheDir(); // cache getFileDir file
path.append(filesDir.getAbsolutePath());// /data/data/com.ldw.market/cache
path.append(File.separator);///data/data/com.ldw.market/cache/
path.append(cache);///data/data/com.ldw.market/cache/cache
}
// 创建一个文件夹。path为其路径
File file = new File(path.toString());
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();// 创建文件夹
}
return file;
}
//判断sd卡是否可用
private static boolean isSDAvailable() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
}
HttpHelper.java封装数据,向网络请求数据
package com.ldw.market.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import android.text.TextUtils;
import com.ldw.market.utils.LogUtils;
import com.lidroid.xutils.util.IOUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class HttpHelper {
public static final String URL = "http://127.0.0.1:8090/";
/** get请求,获取返回字符串内容 */
public static HttpResult get(String url) {
HttpGet httpGet = new HttpGet(url);
return execute(url, httpGet);
}
/** post请求,获取返回字符串内容 */
public static HttpResult post(String url, byte[] bytes) {
HttpPost httpPost = new HttpPost(url);
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(bytes);
httpPost.setEntity(byteArrayEntity);
return execute(url, httpPost);
}
/** 下载 */
public static HttpResult download(String url) {
HttpGet httpGet = new HttpGet(url);
return execute(url, httpGet);
}
/** 执行网络访问 */
private static HttpResult execute(String url, HttpRequestBase requestBase) {
boolean isHttps = url.startsWith("https://");//判断是否需要采用https
AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();//获取重试机制
int retryCount = 0;
boolean retry = true;
while (retry) {
try {
HttpResponse response = httpClient.execute(requestBase, httpContext);//访问网络
if (response != null) {
return new HttpResult(response, httpClient, requestBase);
}
} catch (Exception e) {
IOException ioException = new IOException(e.getMessage());
retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);//把错误异常交给重试机制,以判断是否需要采取从事
LogUtils.e(e);
}
}
return null;
}
/** http的返回结果的封装,可以直接从中获取返回的字符串或者流 */
public static class HttpResult {
private HttpResponse mResponse;
private InputStream mIn;
private String mStr;
private HttpClient mHttpClient;
private HttpRequestBase mRequestBase;
public HttpResult(HttpResponse response, HttpClient httpClient, HttpRequestBase requestBase) {
mResponse = response;
mHttpClient = httpClient;
mRequestBase = requestBase;
}
public int getCode() {
StatusLine status = mResponse.getStatusLine();
return status.getStatusCode();
}
/** 从结果中获取字符串,一旦获取,会自动关流,并且把字符串保存,方便下次获取 */
public String getString() {
if (!TextUtils.isEmpty(mStr)) {
return mStr;
}
InputStream inputStream = getInputStream();
ByteArrayOutputStream out = null;
if (inputStream != null) {
try {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
byte[] data = out.toByteArray();
mStr = new String(data, "utf-8");
} catch (Exception e) {
LogUtils.e(e);
} finally {
IOUtils.closeQuietly(out);
close();
}
}
return mStr;
}
/** 获取流,需要使用完毕后调用close方法关闭网络连接 */
public InputStream getInputStream() {
if (mIn == null && getCode() < 300) {
HttpEntity entity = mResponse.getEntity();
try {
mIn = entity.getContent();
} catch (Exception e) {
LogUtils.e(e);
}
}
return mIn;
}
/** 关闭网络连接 */
public void close() {
if (mRequestBase != null) {
mRequestBase.abort();
}
IOUtils.closeQuietly(mIn);
if (mHttpClient != null) {
mHttpClient.getConnectionManager().closeExpiredConnections();
}
}
}
}