Android Http请求缓存、

package com.flag.http.app.http;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.SocketException;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;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.message.BasicNameValuePair;import android.util.Log;public class Caller {private static final String TAG = "Caller";/** * 缓存最近使用的请求 */private static RequestCache requestCache = null;public static void setRequestCache(RequestCache requestCache) {Caller.requestCache = requestCache;}/** * 使用HttpURLConnection发送Post请求 *  * @param urlPath *            发起服务请求的URL * @param params *            请求头各参数 * @return * @throws SocketException * @throws IOException */public static String doPost(String urlPath, HashMap<String, String> params) throws IOException {String data = null;// 先从缓存获取数据if (requestCache != null) {data = requestCache.get(urlPath);if (data != null) {Log.i(TAG, "Caller.doPost [cached] " + urlPath);return data;}}// 缓存中没有数据,联网取数据// 完成实体数据拼装StringBuilder sb = new StringBuilder();if (params != null && !params.isEmpty()) {for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append('=');sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));sb.append('&');}sb.deleteCharAt(sb.length() - 1);}byte[] entity = sb.toString().getBytes();// 发送Post请求HttpURLConnection conn = null;conn = (HttpURLConnection) new URL(urlPath).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(entity.length));OutputStream outStream = conn.getOutputStream();outStream.write(entity);// 返回数据if (conn.getResponseCode() == 200) {data = convertStreamToString(conn.getInputStream());if (requestCache != null) {requestCache.put(urlPath, data); // 写入缓存,在全局Application里设置Caller的RequestCache对象即可使用缓存机制}return data;}Log.i(TAG, "Caller.doPost Http : " + urlPath);return data;}/** * 使用HttpClient发送Post请求 *  * @param urlPath *            发起请求的Url * @param params *            请求头各个参数 * @return * @throws IOException * @throws ClientProtocolException * @throws SocketException */public static String doPostClient(String urlPath, HashMap<String, String> params) throws IOException {String data = null;// 先从缓存获取数据if (requestCache != null) {data = requestCache.get(urlPath);if (data != null) {Log.i(TAG, "Caller.doPostClient [cached] " + urlPath);return data;}}// 缓存中没有数据,联网取数据// 初始化HttpPost请求头ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();if (params != null && !params.isEmpty()) {for (Map.Entry<String, String> entry : params.entrySet()) {pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}DefaultHttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(urlPath);UrlEncodedFormEntity entity = null;HttpResponse httpResponse = null;try {entity = new UrlEncodedFormEntity(pairs, "UTF-8");post.setEntity(entity);httpResponse = client.execute(post);// 响应数据if (httpResponse.getStatusLine().getStatusCode() == 200) {HttpEntity httpEntity = httpResponse.getEntity();if (httpEntity != null) {InputStream inputStream = httpEntity.getContent();data = convertStreamToString(inputStream);// //将数据缓存if (requestCache != null) {requestCache.put(urlPath, data);}}}} finally {client.getConnectionManager().shutdown();}Log.i(TAG, "Caller.doPostClient Http : " + urlPath);return data;}/** * 使用HttpURLConnection发送Get请求 *  * @param urlPath *            发起请求的Url * @param params *            请求头各个参数 * @return * @throws IOException */public static String doGet(String urlPath, HashMap<String, String> params) throws IOException {String data = null;// 先从缓存获取数据if (requestCache != null) {data = requestCache.get(urlPath);if (data != null) {Log.i(TAG, "Caller.doGet [cached] " + urlPath);return data;}}// 缓存中没有数据,联网取数据// 包装请求头StringBuilder sb = new StringBuilder(urlPath);if (params != null && !params.isEmpty()) {sb.append("?");for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append("=");sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));sb.append("&");}sb.deleteCharAt(sb.length() - 1);}HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString()).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");if (conn.getResponseCode() == 200) {data = convertStreamToString(conn.getInputStream());// //将数据缓存if (requestCache != null) {requestCache.put(urlPath, data);}}Log.i(TAG, "Caller.doGet Http : " + urlPath);return data;}/** * 使用HttpClient发送GET请求 *  * @param urlPath *            发起请求的Url * @param params *            请求头各个参数 * @return * @throws IOException */public static String doGetClient(String urlPath, HashMap<String, String> params) throws IOException {String data = null;// 先从缓存获取数据if (requestCache != null) {data = requestCache.get(urlPath);if (data != null) {Log.i(TAG, "Caller.doGetClient [cached] " + urlPath);return data;}}// 缓存中没有数据,联网取数据// 包装请求头StringBuilder sb = new StringBuilder(urlPath);if (params != null && !params.isEmpty()) {sb.append("?");for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append("=");sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));sb.append("&");}sb.deleteCharAt(sb.length() - 1);}// 实例化 HTTP GET 请求对象HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(sb.toString());HttpResponse httpResponse;try {// 发送请求httpResponse = httpClient.execute(httpGet);// 接收数据HttpEntity httpEntity = httpResponse.getEntity();if (httpEntity != null) {InputStream inputStream = httpEntity.getContent();data = convertStreamToString(inputStream);// //将数据缓存if (requestCache != null) {requestCache.put(urlPath, data);}}} finally {httpClient.getConnectionManager().shutdown();}Log.i(TAG, "Caller.doGetClient Http : " + urlPath);return data;}private static String convertStreamToString(InputStream is) {BufferedReader reader = new BufferedReader(new InputStreamReader(is));StringBuilder sb = new StringBuilder();String line = null;try {while ((line = reader.readLine()) != null) {sb.append(line + "\n");}} catch (IOException e) {e.printStackTrace();} finally {try {is.close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}}


简单的配置:

package com.flag.http.app.http;import java.util.Hashtable;import java.util.LinkedList;public class RequestCache {//缓存的最大个数private static int CACHE_LIMIT = 10;private LinkedList<String> history;private Hashtable<String, String> cache;public RequestCache() {history = new LinkedList<String>();cache = new Hashtable<String, String>();}public void put(String url, String data) {history.add(url);// 超过了最大缓存个数,则清理最早缓存的条目if (history.size() > CACHE_LIMIT) {String old_url = (String) history.poll();cache.remove(old_url);}cache.put(url, data);}public String get(String url) {return cache.get(url);}}


测试:

/** * 全局网络请求缓存 */private RequestCache mRequestCache;@Overridepublic void onCreate() {super.onCreate();mRequestCache = new RequestCache();// 初始化缓存Caller.setRequestCache(mRequestCache);// 给请求设置缓存new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {String json = Caller.doGetClient("URL地址",null);Log.e(json, json);} catch (IOException e) {e.printStackTrace();}}}).start();}




更多相关文章

  1. Android shape 参数
  2. android自带数据库之数据插入
  3. android中的数据库——学习
  4. Android 数据存储之文件存储小记
  5. Android之使用ContentResolver对通信录中的数据进行简单操作
  6. android答题系统(二):实现主界面入口和查询数据
  7. Android跨进程通信传输大数据
  8. 配置android的命令行参数
  9. Android 音频 OpenSL ES PCM数据播放

随机推荐

  1. Android(安卓)Fragment viewPage TabLayo
  2. 【引用】Android的CTS测试
  3. Android触摸屏事件派发机制详解与源码分
  4. Android(安卓): 网络版学生系统
  5. adb pm 指令介绍
  6. Android(安卓)Studio 技巧之【Extract Co
  7. Android心得4.3--SQLite数据库--execSQL(
  8. Android(安卓)Popuwindow使用
  9. Android(安卓)ListView滑动过程中图片显
  10. android获取sdk更新