项目中对网络请求的封装,加入了全局缓存机制

Caller类对HttpURLConnection和HttpClient两种网络访问机制的Post和Get请求都进行了封装,并且加入了全局缓存机制.需要使用缓存机制必须加入RequestCache类,并且在工程的Application类的onCreate方法里进行初始化,并且通过Caller的setRequestCache()方法设置进来.示例如下:

(PS:测试的时候别忘记了添加网络权限和注册Application,否则没有缓存)


Caller类:

package uk.ac.essex.httprequest.util;

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();
	}
}


RequestCache类:

package uk.ac.essex.httprequest.util;

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);
	}
}


工程的Application:

package uk.ac.essex.httprequest;


import uk.ac.essex.httprequest.util.Caller;
import uk.ac.essex.httprequest.util.RequestCache;
import android.app.Application;

public class DemoApplication extends Application {

	/**
	 * 全局网络请求缓存
	 */
	private RequestCache mRequestCache;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		mRequestCache = new RequestCache();//初始化缓存
		Caller.setRequestCache(mRequestCache);//给请求设置缓存
	}
}





你可能感兴趣的:(项目中对网络请求的封装,加入了全局缓存机制)