关闭

android HttpURLConnection ,HttpClient设置Cookie

标签: androidcookie设置
9679人阅读 评论(2) 收藏 举报
分类:


上一阶段项目设计使用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);
        }
        
    }

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:652780次
    • 积分:4292
    • 等级:
    • 排名:第7335名
    • 原创:38篇
    • 转载:1篇
    • 译文:0篇
    • 评论:143条
    博客专栏
    最新评论