Android http请求类添加Cookie

本文详细介绍了如何使用Apache HttpClient库进行HTTP请求的构造及处理,包括GET和POST请求方式,参数传递,以及如何处理响应数据和管理会话状态。同时,文章还涉及了网络连接配置、超时设置和异常处理等关键点。
摘要由CSDN通过智能技术生成
package com.test.app;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
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.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.StrictMode;
import android.util.Log;

/**
 * 请求数据
 * 
 * @author Administrator
 * 
 */
public class HttpClientTool {

	public String TIME_OUT = "操作延时";
	public int time = 20000;
	/** 当前会话后的cokie信息 */
	private static CookieStore uCookie = null;

	/** 得到上下文 **/
	private Context context;

	public HttpClientTool(Context context) {
		this.context = context;
	}

	public CookieStore getuCookie() {
		return uCookie;
	}

	public void setuCookie(CookieStore uCookie) {
		this.uCookie = uCookie;
	}

	/** 得到设备信息、系统版本、驱动类型 **/
	private Header[] getHeader() {
		/** 请求头信息 end **/
		MyHttpCookies li = new MyHttpCookies(context);
		return li.getHttpHeader();
	}

	/**
	 * 请求数据--带param参数.
	 * 
	 * @param params
	 * @param url
	 * @return
	 */
	public String doPost(List<NameValuePair> params, String url) {
		network();
		String result = null;
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeaders(this.getHeader());
		System.out.println("---->url=" + url);

		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));

			/** 保持会话Session **/
			/** 设置Cookie **/
			MyHttpCookies li = new MyHttpCookies(context);
			CookieStore cs = li.getuCookie();
			/** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
			if (cs != null) {
				httpClient.setCookieStore(li.getuCookie());
			}
			/** 保持会话Session end **/
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, time);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, time);
			HttpResponse httpResp = httpClient.execute(httpPost);
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
				Log.i("HttpPost", "HttpPost方式请求成功,返回数据如下:");
				Log.i("result", result);
				/** 执行成功之后得到 **/
				/** 成功之后把返回成功的Cookis保存APP中 **/
				// 请求成功之后,每次都设置Cookis。保证每次请求都是最新的Cookis
				li.setuCookie(httpClient.getCookieStore());
				/** 设置Cookie end **/
			} else {
				Log.i("HttpPost", "HttpPost方式请求失败");
				System.out.println("0000===>" + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
				result = "{status:'0',message:'请求失败'}";
			}
		} catch (SocketTimeoutException e) {
			result = "{status:'0',message:'" + TIME_OUT + "'}";
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			result = "{status:'0',message:'请求失败'}";
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			result = "{status:'0',message:'请求失败'}";
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.abort();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * 请求数据,未带参数.
	 * 
	 * @param url
	 * @return
	 */
	public String doPost(String url) {
		network();
		String result = null;
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeaders(this.getHeader());
		System.out.println("---->url=" + url);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {

			/** 保持会话Session **/
			/** 设置Cookie **/
			MyHttpCookies li = new MyHttpCookies(context);
			CookieStore cs = li.getuCookie();
			/** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
			if (cs != null) {
				httpClient.setCookieStore(li.getuCookie());
			}
			/** 保持会话Session end **/
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, time);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, time);
			HttpResponse httpResp = httpClient.execute(httpPost);
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
				Log.i("HttpPost", "HttpPost方式请求成功,返回数据如下:");
				Log.i("result", result);
				/** 执行成功之后得到 **/
				/** 成功之后把返回成功的Cookis保存APP中 **/
				// 请求成功之后,每次都设置Cookis。保证每次请求都是最新的Cookis
				li.setuCookie(httpClient.getCookieStore());
				/** 设置Cookie end **/
			} else {
				Log.i("HttpPost", "HttpPost方式请求失败");
				System.out.println("0000===>" + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
				result = "{success:false,msg:'请求失败'}";
			}
		} catch (SocketTimeoutException e) {
			result = "{status:'0',message:'" + TIME_OUT + "'}";
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			result = "{status:'0',message:'请求失败'}";
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			result = "{status:'0',message:'请求失败'}";
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * get 请求构造url
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public String doGet(List<NameValuePair> params, String url) {
		/** 建立HTTPGet对象 **/
		String paramStr = "";
		if (params == null)
			params = new ArrayList<NameValuePair>();
		/** 迭代请求参数集合 **/
		for (NameValuePair obj : params) {
			paramStr += paramStr = "&" + obj.getName() + "=" + URLEncoder.encode(obj.getValue());
		}
		if (!paramStr.equals("")) {
			paramStr = paramStr.replaceFirst("&", "?");
			url += paramStr;
		}
		System.out.println("do_get_url ==== >" + url);
		return doGet(url);
	}

	/**
	 * 提供GET形式的访问网络请求 doGet 参数示例:
	 * 
	 * @param url
	 *            请求地址
	 * @return 返回 String jsonResult;
	 * 
	 */
	public String doGet(String url) {
		System.out.println("url===>" + url);
		network();
		/** 创建HttpGet对象 **/
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeaders(this.getHeader());

		DefaultHttpClient httpClient = new DefaultHttpClient();
		String result;
		try {
			/** 保持会话Session **/
			/** 设置Cookie **/
			MyHttpCookies li = new MyHttpCookies(context);
			CookieStore cs = li.getuCookie();
			/** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
			if (cs != null) {
				httpClient.setCookieStore(li.getuCookie());
			}
			/** 保持会话Session end **/
			/* 发送请求并等待响应 */
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, time);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, time);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
				Log.i("HttpPost", "HttpGet方式请求成功,返回数据如下:");
				Log.i("result", result);
				li.setuCookie(httpClient.getCookieStore());
			} else {
				Log.i("HttpPost", "HttpGet方式请求失败");
				result = "{status:'0',message:'请求失败'}";
				System.out.println("0000===>" + EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
			}
		} catch (ClientProtocolException e) {
			result = e.getMessage();
			e.printStackTrace();
		} catch (IOException e) {
			result = e.getMessage();
			e.printStackTrace();
		} catch (Exception e) {
			result = e.getMessage();
			httpGet.abort();
			// 销毁HttpClient
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	@SuppressLint("NewApi")
	private void network() {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork() // or .detectAll() for all detectable problems
				.build());
	}
}

/**
 * http请求的缓存和一些公用的参数
 * 
 * @author Administrator
 */
class MyHttpCookies {
	/** 每页数据显示最大数 */
	private static int pageSize = 10;
	/** 当前会话后的cokie信息 */
	private static CookieStore uCookie = null;
	/** 公用的HTTP提示头信息 */
	private static Header[] httpHeader;
	/** HTTP连接的网络节点 */
	private static String httpProxyStr;
	/** http请求的公用url部分 **/
	public static String baseurl = "http://www.2cto.com /River";
	/** 上下文对象 **/
	Context context;

	public MyHttpCookies(Context context) {
		this.context = context;
		/** y设置请求头 **/
		/** y设置请求头 **/
		Header[] header = {new BasicHeader("PagingRows", String.valueOf(pageSize))};
		httpHeader = header;
	}

	/**
	 * 增加自动选择网络,自适应cmwap、CMNET、wifi或3G
	 */
	@SuppressWarnings("static-access")
	public void initHTTPProxy() {
		WifiManager wifiManager = (WifiManager) (context.getSystemService(context.WIFI_SERVICE));
		if (!wifiManager.isWifiEnabled()) {
			Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点
			Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
			if (mCursor != null) {
				mCursor.moveToNext(); // 游标移至第一条记录,当然也只有一条
				httpProxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
			}
		} else {
			httpProxyStr = null;
		}
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public CookieStore getuCookie() {
		return uCookie;
	}

	public void setuCookie(CookieStore uCookie) {
		this.uCookie = uCookie;
	}

	public Header[] getHttpHeader() {
		return httpHeader;
	}

	public String getHttpProxyStr() {
		return httpProxyStr;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值