Android Http RequestCache缓存策略

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;

	@Override
	public void onCreate() {
		super.onCreate();

		mRequestCache = new RequestCache();// 初始化缓存
		Caller.setRequestCache(mRequestCache);// 给请求设置缓存
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String json = Caller
							.doGetClient(
									"URL地址",
									null);
					Log.e(json, json);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();

	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值