Android · 2014年11月24日 0

Android 上的 HttpClient 的 Cookie 存取策略

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;

}

Share this: