android HttpURLConnection ,HttpClient设置Cookie

原创 2015年07月06日 18:35:08


上一阶段项目设计使用cookie信息实现登录访问功能,在实现过程遇到一些问题,下面整理一下:

首先,client想使用cookie,必须访问一次server从会话中获取cookie信息,然后在设置回去,在android使用HttpURLConnection 直接设置会报异常

查阅文档及StackOver发现android需要使用CookieManager进行处理cookie相关信息,实现如下:

 InputStream input = null;
        OutputStream output = null;

        HttpURLConnection connection = null;
        try {
            java.net.CookieManager manager = new java.net.CookieManager();
            manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(manager);

            URL url = new URL(dnUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            connection.connect();

            connection.getHeaderFields();
            CookieStore store = manager.getCookieStore();

            int resultCode=connection.getResponseCode();
            responseUpdateCookieHttpURL(store);
           //  expect HTTP 200 OK, so we don't mistakenly save error report
           //  instead of the file
            if (resultCode != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

  /**
     * 更新本地Cookie信息
     */
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void responseUpdateCookieHttpURL(CookieStore store) {
        boolean needUpdate = false;
        List<HttpCookie> cookies = store.getCookies();
        HashMap<String, String> cookieMap = null;
        if (cookieMap == null) {
            cookieMap = new HashMap<String, String>();
        }
        for (HttpCookie cookie : cookies) {
            String key = cookie.getName();
            String value = cookie.getValue();
            if (cookieMap.size() == 0 || !value.equals(cookieMap.get(key))) {
                needUpdate = true;
            }
            cookieMap.put(key, value);
    //        BDebug.e(HTTP_COOKIE, cookie.getName() + "---->" + cookie.getDomain() + "------>" + cookie.getPath());
        }
        
    }

 public static final int GET = 0;
    public static final int POST = 1;
    public static final String HTTP_POST_BODY = "body";
    public static final String HTTP_COOKIE = "Cookie";
    public static final String HTTP_USER_AGENT = "User-Agent";

HttpClient实现更改设置Cookie信息:

void handleCookie(String url){
		
		try{
			HttpClient client = new DefaultHttpClient();  
		    HttpGet httpget = new HttpGet(url);  
		    HttpResponse httpResponse = client.execute(httpget);  
		
		    int responseCode = httpResponse.getStatusLine().getStatusCode();

            HttpBuilder.responseUpdateCookieHttpClient((DefaultHttpClient)client);

            if (responseCode == HttpStatus.SC_OK) {
                /*result = EntityUtils.toString(httpResponse.getEntity());
                HttpEntity entity = response.getEntity();  
                InputStream is = entity.getContent();*/
            }
		}catch(Exception e){
			e.printStackTrace();
		}
	}

   /**
     * 获取cookie信息
     * 
     * @param cookieMap
     * @return
     */
    public static String getCookieInfo(HashMap<String, String> cookieMap) {
        StringBuilder cookieInfo = new StringBuilder();
        if (cookieMap != null && cookieMap.size() > 0) {
            Iterator<Entry<String, String>> iter = cookieMap.entrySet().iterator();
            Entry<String, String> entry;
            while (iter.hasNext()) {
                String key = "";
                String value = "";
                entry = iter.next();
                key = entry.getKey();
                value = entry.getValue();
                cookieInfo.append(key).append("=").append(value).append(";");
            }
        }
        return cookieInfo.toString();
    }

    /**
     * 更新本地Cookie信息
     * 
     * @param defaultHttpClient
     */
    public static void responseUpdateCookieHttpClient(DefaultHttpClient defaultHttpClient) {
        boolean needUpdate = false;
        List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
        HashMap<String, String> cookieMap = null;
        if (cookieMap == null) {
            cookieMap = new HashMap<String, String>();
        }
        for (Cookie cookie : cookies) {
            String key = cookie.getName();
            String value = cookie.getValue();
            if (cookieMap.size() == 0 || !value.equals(cookieMap.get(key))) {
                needUpdate = true;
            }
            cookieMap.put(key, value);
        }
        
    }

基本就这些,有问题留言。



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Android-HttpURLConnection自动管理cookie

Volley那么好用的框架竟然没有内置对cookie的处理,自己搞一个!public class MobCookieManager { private MobCookieManager(){} ...

HttpURLConnection与 CookieManager 实现Post提交请求和Cookie管理

下面是我的疑问,为什么直接注入cookie 不可以?
  • heyu158
  • heyu158
  • 2014年04月10日 11:51
  • 44674

HttpURLConnection使用cookie

利用HttpURLConnection进行网络请求,需要使用cookie,走了一些弯路,现在的方案是使用cookiemanager。 参考: android 给url添加cookie HttpURL...

Pro Android学习笔记(七二):HTTP服务(6):HttpURLConnection

文章转载只能用于非商业性质,且不能带有虚拟货币、积分、注册等附加条件,转载须注明出处:http://blog.csdn.net/flowingflying/ 之前我们都是使用HttpClient来进行...

httpurlconnection中设置cookie的时机问题

http://blog.csdn.net/archer_zoro/article/details/42041883 遇到一个问题,先记录一下: 在用httpurlconnection进...

android学习笔记之利用AsyncHttpClient实现登录及cookie使用

android通过AsyncHttpClient实现客户端登录及cookie保存

android httpclient与webview cookie同步

1,在登陆成功的时候定义一个全局变量将cookie缓存起来       public static void saveCookie(DefaultHttpClient httpClient,Co...

Android Http get和post请求,URLConnection以及Cookie的处理

Post请求 public static String httpPost(String url) { String username = "", password = ""; String ...

Android http请求类添加Cookie

package com.easyder.util; import java.io.IOException; import java.io.UnsupportedEncodingException; ...

Android本地化存储Cookie(针对HttpClient)

因为最近有人问我怎么保存HttpClient的Cookie, 所以这里写下, 顺便记录总结吧. 当然, 有Android网络编程经历的童鞋一看就懂喇~  就不多说了, 直接上代码: /**...
  • stzy00
  • stzy00
  • 2015年07月08日 17:54
  • 1787
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:android HttpURLConnection ,HttpClient设置Cookie
举报原因:
原因补充:

(最多只允许输入30个字)