NetUtil工具类
来源:互联网 发布:拍婚纱照 知乎 编辑:程序博客网 时间:2024/05/17 16:44
package com.itheima.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
import android.util.Log;
import com.itheima.gooleplay.MyApp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.core.AsyncDrawable;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.IOUtils;
public class NetUtil {
protected static final Object TAG = NetUtil.class;
private static BufferedWriter writer;
public static void requestData(String url, Map<String, String> params, JsonRequestCallBack jsonRequestCallBack) {
//获得一个get 请求,设置请求参数
String requestUrl = createRequestUrl(url,params);
//获取缓存文件
File cacheFile = getCateFile(requestUrl);
//判断缓存文件是否有用
if (cacheFileIsUseable(cacheFile)) {
//有用的话就直接使用,从缓存中读取json
getDataFromCache(cacheFile,jsonRequestCallBack);
}else {
//如果缓存无效,就直接访问网络
getDataFromNet(requestUrl,jsonRequestCallBack);
}
}
//从网络中读取数据
private static void getDataFromNet(final String requestUrl, final JsonRequestCallBack jsonRequestCallBack) {
HttpUtils http = new HttpUtils();
RequestCallBack<String> requestCallBack = new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String json = responseInfo.result;
//写到缓存中
writeCacheFile(json,requestUrl);
jsonRequestCallBack.onRequestFinish(json);
}
@Override
public void onFailure(HttpException error, String msg) {
Logger.e(TAG, "网络请求失败"+msg, error);
jsonRequestCallBack.onRequestFinish(null);
}
};
http.send(HttpMethod.GET, requestUrl, requestCallBack);
}
protected static void writeCacheFile(String json,String requestUrl) {
try {
File cacheFile= new File(requestUrl);
writer = new BufferedWriter(new FileWriter(cacheFile));
writer.write(json);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(writer);
}
}
//从缓存中读取json
private static void getDataFromCache(final File cacheFile, final JsonRequestCallBack jsonRequestCallBack) {
//读取缓存 ,是耗时操作
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(cacheFile));
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine())!=null) {
sb.append(line).append("\n");
}
String result = sb.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(reader);
}
return null;
}
@Override
protected void onPostExecute(String result) {
//Logger.i(TAG, "我是缓存中的数据"+result);
//super.onPostExecute(result);
jsonRequestCallBack.onRequestFinish(result);
}
}.execute();
}
private static boolean cacheFileIsUseable(File cacheFile) {
//判断缓存文件是否有效的方法
if (cacheFile == null || !cacheFile.exists()) {
return false;
}
//当前的时间 - 缓存文件最后一次的修改时间
long existTime = System.currentTimeMillis()-cacheFile.lastModified();
//规定有效的存在的时间是3分钟
long ExitTime = 3*60*1000;
return existTime < ExitTime;
}
private static File getCateFile(String requestUrl) {
/** 获取data/data/com.itheima.googleplay/cache/目录下的缓存文件 */
try {
requestUrl = URLEncoder.encode(requestUrl, HTTP.UTF_8);
File cacheFile = new File(MyApp.getContext().getCacheDir(), requestUrl);
return cacheFile;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
*http://127.0.0.1:8090/subject?index=0
*
*把url和params 进行拼接
* @return
*/
private static String createRequestUrl(String url, Map<String, String> params) {
if (params == null || params.isEmpty()) {
return url;
}
//取出HashMap中所有的key
Set<String> keySet = params.keySet();
//把set转换成list,便于排序
ArrayList<String> keys = new ArrayList<String>(keySet);
Collections.sort(keys);
StringBuffer sb = new StringBuffer();
//// 把参数拼接成:&name=zhangsan&age=45&score=99
for (String key : keys) {
sb.append("&").append(key).append("=").append(params.get(key));
}
//删除第一个字符
sb.deleteCharAt(0);
//拼接url 和参数
String requestUrl = url+"?"+ sb.toString();
return requestUrl;
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
import android.util.Log;
import com.itheima.gooleplay.MyApp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.core.AsyncDrawable;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.IOUtils;
public class NetUtil {
protected static final Object TAG = NetUtil.class;
private static BufferedWriter writer;
public static void requestData(String url, Map<String, String> params, JsonRequestCallBack jsonRequestCallBack) {
//获得一个get 请求,设置请求参数
String requestUrl = createRequestUrl(url,params);
//获取缓存文件
File cacheFile = getCateFile(requestUrl);
//判断缓存文件是否有用
if (cacheFileIsUseable(cacheFile)) {
//有用的话就直接使用,从缓存中读取json
getDataFromCache(cacheFile,jsonRequestCallBack);
}else {
//如果缓存无效,就直接访问网络
getDataFromNet(requestUrl,jsonRequestCallBack);
}
}
//从网络中读取数据
private static void getDataFromNet(final String requestUrl, final JsonRequestCallBack jsonRequestCallBack) {
HttpUtils http = new HttpUtils();
RequestCallBack<String> requestCallBack = new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String json = responseInfo.result;
//写到缓存中
writeCacheFile(json,requestUrl);
jsonRequestCallBack.onRequestFinish(json);
}
@Override
public void onFailure(HttpException error, String msg) {
Logger.e(TAG, "网络请求失败"+msg, error);
jsonRequestCallBack.onRequestFinish(null);
}
};
http.send(HttpMethod.GET, requestUrl, requestCallBack);
}
protected static void writeCacheFile(String json,String requestUrl) {
try {
File cacheFile= new File(requestUrl);
writer = new BufferedWriter(new FileWriter(cacheFile));
writer.write(json);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(writer);
}
}
//从缓存中读取json
private static void getDataFromCache(final File cacheFile, final JsonRequestCallBack jsonRequestCallBack) {
//读取缓存 ,是耗时操作
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(cacheFile));
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine())!=null) {
sb.append(line).append("\n");
}
String result = sb.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(reader);
}
return null;
}
@Override
protected void onPostExecute(String result) {
//Logger.i(TAG, "我是缓存中的数据"+result);
//super.onPostExecute(result);
jsonRequestCallBack.onRequestFinish(result);
}
}.execute();
}
private static boolean cacheFileIsUseable(File cacheFile) {
//判断缓存文件是否有效的方法
if (cacheFile == null || !cacheFile.exists()) {
return false;
}
//当前的时间 - 缓存文件最后一次的修改时间
long existTime = System.currentTimeMillis()-cacheFile.lastModified();
//规定有效的存在的时间是3分钟
long ExitTime = 3*60*1000;
return existTime < ExitTime;
}
private static File getCateFile(String requestUrl) {
/** 获取data/data/com.itheima.googleplay/cache/目录下的缓存文件 */
try {
requestUrl = URLEncoder.encode(requestUrl, HTTP.UTF_8);
File cacheFile = new File(MyApp.getContext().getCacheDir(), requestUrl);
return cacheFile;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
*http://127.0.0.1:8090/subject?index=0
*
*把url和params 进行拼接
* @return
*/
private static String createRequestUrl(String url, Map<String, String> params) {
if (params == null || params.isEmpty()) {
return url;
}
//取出HashMap中所有的key
Set<String> keySet = params.keySet();
//把set转换成list,便于排序
ArrayList<String> keys = new ArrayList<String>(keySet);
Collections.sort(keys);
StringBuffer sb = new StringBuffer();
//// 把参数拼接成:&name=zhangsan&age=45&score=99
for (String key : keys) {
sb.append("&").append(key).append("=").append(params.get(key));
}
//删除第一个字符
sb.deleteCharAt(0);
//拼接url 和参数
String requestUrl = url+"?"+ sb.toString();
return requestUrl;
}
}
0 0
- NetUtil工具类
- 工具类NetUtil
- Android工具类系列-NetUtil
- 网络请求get/post工具类:NetUtil
- 工具类--NetUtil 判断网络状态
- NetUtil
- NetUtil
- AS3 NetUtil浏览器实用类
- 【常用工具类】NetUtil(检测当前网络状态)
- android NetUtil
- NETUtil IP是否可达
- tornado.netutil — Miscellaneous network utilities 杂项网络工具
- NetUtil 有关于IP端口的简单校验和操作
- 工具类
- 工具类!!!!
- 工具类
- 工具类
- 工具类
- 最新Android之支持多进程、多线程的TrayPreferences代替SharedPreferences 的总结
- Unity小知识
- Android中签名、证书、公钥密钥的概念及使用
- Android 5.0以上系统背景色白色的那些坑
- MySql集群知识与搭建--源自技术
- NetUtil工具类
- hdu 5044 Tree(树链剖分)
- 数据结构上机测试2-2:单链表操作B
- Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/ServletContext
- 如何在while(cin>>str)跳出循环后能继续执行程序中其他的输入操作
- 大数据寻宝之关联挖掘
- spring加载properties文件顺序
- MyBatis中select语句
- AVL树常用算法算法