項目中對網絡請求的封裝,加入了全局緩存機制

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);//給請求設置緩存
	}
}

 連接地址:http://blog.csdn.net/hexingzhi/article/details/7425752

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章