zoukankan      html  css  js  c++  java
  • android HttpURLConnection ,HttpClient设置Cookie


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

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



  • 相关阅读:
    error LNK2001: unresolved external symbol "public: __thiscall ControllerInterface::ControllerInterface(class QObject *)" (??0ControllerInterface@@QAE@PAVQObject@@@Z) downloadcontroller.obj
    链接程序的时候遇到问题:fatal error LNK1104: cannot open file 'rctrl-d.lib'
    vs编译报错 BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
    qt 编译unresolved external symbol的错误解决
    程序外框不显示
    Pc移植到Mac的技术细节
    qt中moc的作用
    做回自己,保持作为一个男人的魅力是维持一个维持一段恋爱关系长久的前提
    NLP入门(三)词形还原(Lemmatization)
    NLP入门(二)探究TF-IDF的原理
  • 原文地址:https://www.cnblogs.com/happyxiaoyu02/p/6212956.html
Copyright © 2011-2022 走看看