Android 上的 HttpClient 的 Cookie 存取策略

本文详细介绍了如何使用默认HTTP客户端进行HTTP请求,并通过自定义Cookie策略管理会话Cookie。包括设置连接超时、Socket超时、总超时,创建CookieStore与自定义CookieSpec,以及如何将自定义CookieSpec注册到客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:http://blog.youkuaiyun.com/zdl_411437734/article/details/41432019
BasicHttpParams params = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established. 
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data. 
HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); 
 
ConnManagerParams.setMaxTotalConnections(params, 5);
ConnManagerParams.setTimeout(params, TIMEOUT_TOTAL);
 
client = new DefaultHttpClient(params);
 
CookieStore cookieStore = new BasicCookieStore();
//Bind custom cookie store to the local context
client.setCookieStore(cookieStore);
CookieSpecFactory csf = new CookieSpecFactory() {          
public CookieSpec newInstance(HttpParams params) {
    return new BrowserCompatSpec() {
    @Override
    public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException 
    {
        // Oh, I am easy
        // allow all cookies
        //log.debug("custom validate");
    }
    };
}
};
client.getCookieSpecs().register("oschina", csf);
client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "oschina");
client.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);


当然下面设置也可以,直接运行下就能看到结果。。

/**

@param url

*            :交互服务器的URL地址

@param pairs

*            :交互所带的参数

@return JSONObject:从服务器获取的字符串

*/

public static String httpServicePostString(String url,

List<BasicNameValuePair> pairs, Context context) {

HttpPost httpPost = new HttpPost(url);

DefaultHttpClient httpClient = new DefaultHttpClient();

Log.d("cat",

"out response=" + httpPost.getURI() + "  " + pairs.toString());

try {

httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));

catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

CookieStore cookieStore = new BasicCookieStore();

httpClient.setCookieStore(cookieStore);

try {

HttpResponse response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

HttpEntity httpEntity = response.getEntity();

if (httpEntity != null) {

CookieStore c = httpClient.getCookieStore();

List<Cookie> list = c.getCookies();

for (Cookie cookie : list) {

Log.e(HttpService.class.getName(),

"cookie=" + cookie.getName());

Log.e(HttpService.class.getName(),

"cookie=" + cookie.getValue()+"-"+cookie.getComment()+"--"+cookie.getCommentURL());

Log.e(HttpService.class.getName(),

"cookie=" + cookie.getDomain()+"-"+cookie.getPath()+"--"+cookie.getVersion());

SharedPreferencesUtils sharePrefenrences = new SharedPreferencesUtils();

sharePrefenrences.saveCookie(context, cookie.getValue());

}

Header[] headers = response.getAllHeaders();

for (Header header : headers) {


Log.e(HttpService.class.getName(),

"head=" + header.getName());

}

if (response.getFirstHeader("Set-Cookie") != null) {

String set_cookie = response.getFirstHeader(

"Set-Cookie").getValue();

Log.e(HttpService.class.getName(), "set_cookie="

+ set_cookie);

SharedPreferencesUtils sharePrefenrences = new SharedPreferencesUtils();

sharePrefenrences.saveCookie(context, set_cookie);

}

InputStream inputStream = httpEntity.getContent();

BufferedReader bufferReader = new BufferedReader(

new InputStreamReader(inputStream), i);

String returnStr = "";

String readLine = null;

while ((readLine = bufferReader.readLine()) != null) {

returnStr = returnStr + readLine;

}

inputStream.close();

bufferReader.close();

Log.d("cat""returnStr=" + returnStr);

return returnStr;

}

}

catch (ClientProtocolException e) {

e.printStackTrace();

returnnull;

catch (IOException e) {

e.printStackTrace();

returnnull;

}

returnnull;

}

更多文章查看个人博客:http://blog.etongwl.com


转载请注明出处:http://blog.youkuaiyun.com/zdl_411437734/article/details/41432019

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值