android中如何处理cookie

Managing Cookies

HttpClient provides cookie management features that can be particularly useful to test the way an application handles cookies. Listing 9-3 shows an example where you use HttpClient to add a cookie to a request and also to list details of cookies set by the JSP you invoke using the HttpClient code.

The HttpState class plays an important role while working with cookies. The HttpState class works as a container for HTTP attributes such as cookies that can persist from one request to another. When you normally surf the Web, the Web browser is what stores the HTTP attributes.

Listing 9-3. CookiesTrial.java
package com.commonsbook.chap9;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;

public class CookiesTrial {

    private static String url =
         "http://127.0.0.1:8080/HttpServerSideApp/CookieMgt.jsp";

    public static void main(String[] args) throws Exception {

        //A new cookie for the domain 127.0.0.1
        //Cookie Name= ABCD   Value=00000   Path=/  MaxAge=-1   Secure=False
        Cookie mycookie = new Cookie("127.0.0.1", "ABCD", "00000", "/", -1, false);

        //Create a new HttpState container
        HttpState initialState = new HttpState();
        initialState.addCookie(mycookie);

        //Set to COMPATIBILITY for it to work in as many cases as possible
        initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        //create new client
        HttpClient httpclient = new HttpClient();
        //set the HttpState for the client
        httpclient.setState(initialState);

        GetMethod getMethod = new GetMethod(url);
        //Execute a GET method
        int result = httpclient.executeMethod(getMethod);

        System.out.println("statusLine>>>"+getMethod.getStatusLine());

        //Get cookies stored in the HttpState for this instance of HttpClient
        Cookie[] cookies = httpclient.getState().getCookies();

        for (int i = 0; i < cookies.length; i++) {
            System.out.println("nCookieName="+cookies[i].getName());
            System.out.println("Value="+cookies[i].getValue());
            System.out.println("Domain="+cookies[i].getDomain());
        }

        getMethod.releaseConnection();
    }
}

In Listing 9-3, you use the HttpState instance to store a new cookie and then associate this instance with theHttpClient instance. You then invoke CookieMgt.jsp. This JSP is meant to print the cookies it finds in the request and then add a cookie of its own. The JSP code is as follows:

<%
        Cookie[] cookies= request.getCookies();

        for (int i = 0; i < cookies.length; i++) {
          System.out.println(cookies[i].getName() +" = "+cookies[i].getValue());
        }

        //Add a new cookie
        response.addCookie(new Cookie("XYZ","12345"));
%>

CAUTION HttpClient code uses the class org.apache.commons.httpclient.Cookie, and JSP and servlet code uses the class javax.servlet.http.Cookie.

The output on the application console upon executing the CookiesTrial class and invoking CookieMgt.jsp is as follows:

statusLine>>>HTTP/1.1 200 OK

CookieName=ABCD
Value=00000
Domain=127.0.0.1

CookieName=XYZ
Value=12345
Domain=127.0.0.1

CookieName=JSESSIONID
Value=C46581331881A84483F0004390F94508
Domain=127.0.0.1

In this output, note that although the cookie named ABCD has been created from CookiesTrial, the other cookie named XYZ is the one inserted by the JSP code. The cookie named JSESSIONID is meant for session tracking and gets created upon invoking the JSP. The output as displayed on the console of the server when the JSP is executed is as follows:

ABCD = 00000

This shows that when CookieMgt.jsp receives the request from the CookiesTrial class, the cookie namedABCD was the only cookie that existed. The sidebar “HTTPS and Proxy Servers” shows how you should handle requests over HTTPS and configure your client to go through a proxy.


HTTPS and Proxy Servers

Using HttpClient to try out URLs that involve HTTPS is the same as with ordinary URLs. Just state https://… as your URL, and it should work fine. You only need to have Java Secure Socket Extension (JSSE) running properly on your machine. JSSE ships as a part of Java Software Development Kit (JSDK) 1.4 and higher and does not require any separate download and installation.

If you have to go through a proxy server, introduce the following piece of code. Replace PROXYHOST with the host name and replace 9999 with the port number for your proxy server:

   HttpClient client = new HttpClient();
HostConfiguration hConf= client.getHostConfiguration();
hConf.setProxy("PROXYHOST ", 9999);

If you also need to specify a username password for the proxy, you can do this using the setProxyCredentials method of the class HttpState. This method takes a Credentials object as a parameter. Credentials is a marker interface that has no methods and has a single implementation UsernamePasswordCredentials. You can use this class to create a Credentials object that holds the username and password required for Basic authentication.

You will now see the HttpClient component’s capability to use MultipartPostMethod to upload multiple files. You will look at this in tandem with the Commons FileUpload component. This Commons component is specifically meant to handle the server-side tasks associated with file uploads.

Introducing FileUpload

The FileUpload component has the capability of simplifying the handling of files uploaded to a server. Note that the FileUpload component is meant for use on the server side; in other words, it handles where the files are being uploaded to—not the client side where the files are uploaded from. Uploading files from an HTML form is pretty simple; however, handling these files when they get to the server is not that simple. If you want to apply any rules and store these files based on those rules, things get more difficult.

The FileUpload component remedies this situation, and in very few lines of code you can easily manage the files uploaded and store them in appropriate locations. You will now see an example where you upload some files first using a standard HTML form and then using HttpClient code.

android中如何处理cookie

时间: 2024-10-05 10:14:27

android中如何处理cookie的相关文章

如何处理Android中的防缓冲区溢出技术

[51CTO专稿]本文将具体介绍Android中的防缓冲区溢出技术的来龙去脉. 1.什么是ASLR? ASLR(Address space layout randomization)是一种针对缓冲区溢出的安全保护技术,通过对堆.栈.共享库映射等线性区布局的随机化.通过添加攻击者预測目的地址的难度.防止攻击者直接定位攻击代码位置,达到阻止溢出攻击的目的.通常情况下.黑客会利用某个特定函数或库驻存在特定内存位置的这一事实.通过在操纵堆或其它内存错误时调用该函数来发动攻击.ASLR则可以避免这样的情况

Token在android中的使用

首先Token是一个怎么样的东西,Token存在的意义又在哪里?学过php或是其他web开发的人都知道一个东西叫session和cookie,这些东西可以在服务器或是本地保存一些东西,比如说登录状态,当用户登录后可以通过session或是cookie在本地保存一段时间的登录状态,在这段时间内,用户再度登录的时候就不用再输入用户名和密码了,但是过了一段时间后,用户需要再次进行身份认证,这样一来的话,一方面节省了很多操作的步骤提升了操作体验,同时也节省了很多服务器请求,提高了服务器性能,同时也保证了

Android中通过访问本地相册或者相机设置用户头像

目前几乎所有的APP在用户注册时都会有设置头像的需求,大致分为三种情况: (1)通过获取本地相册的图片,经过裁剪后作为头像. (2)通过启动手机相机,现拍图片然后裁剪作为头像. (3)在APP中添加一些自带的头像资源,供用户选择(不够人性化,目前很少使用). 这次我们简单介绍下通过获取本地相册以及相机拍摄的方法设置头像,实现思路如下: (1)通过startActivityForResult方法,分别传递调用系统相册的Intent和调用相机拍照的Intent来做选择 (2)调用Android系统中

Android中的事件分发机制(下)——View的事件处理

综述 在上篇文章Android中的事件分发机制(上)--ViewGroup的事件分发中,对ViewGroup的事件分发进行了详细的分析.在文章的最后ViewGroup的dispatchTouchEvent方法调用dispatchTransformedTouchEvent方法成功将事件传递给ViewGroup的子View.并交由子View进行处理.那么现在就来分析一下子View接收到事件以后是如何处理的. View的事件处理 对于这里描述的View,它是ViewGroup的父类,并不包含任何的子元

Android中事件传递机制的总结

事件传递虽然算不上某个单独的知识点,但是在实际项目开发中肯定会碰到,如果不明白其中的原理,那在设计各种滑动效果时就会感到很困惑. 关于事件的传递,我们可能会有以下疑问: 事件是如何传递的 事件是如何处理的 自定义view的时候,事件也冲突了怎么解决 带着这三个疑问,我们来总结一下事件传递机制是怎么回事. 一.事件分发的原理: 1.事件是如何传递的: (1)首先由Activity分发,分发给根View,也就是DecorView(DecorView为整个Window界面的最顶层View) (2)然后

管窥Android中的滑动条SeekBar的父类AbsSeekBar的源码

Android中的控件中有一类是ProgressBar,其子类中有一个是AbsSeekBar.相信有不少童鞋对这个拖动条的父类比较感兴趣吧!尤其是看到网易云音乐的进度条上面是可以处理播放与暂停事件,是不是很羡慕的哈~  俺在这里告诉大家,不用羡慕,看了我下面的代码分析,你也是可以做出那样的效果的哦.Let's go. 下面先给大家列表一下AbsSeekBar的成员变量有哪些. //当前的矩形 private final Rect mTempRect = new Rect(); //可以拖动的滑块

Android中的缓存处理

一.缓存介绍 (一).Android中缓存的必要性: 1.没有缓存的弊端: 流量开销:对于客户端--服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量. 加载速度:如果应用中图片加载速度很慢的话,那么用户体验会非常糟糕. 那么如何处理好图片资源的获取和管理呢?异步下载+本地缓存 2.缓存带来的好处: 1. 服务器的压力大大减小: 2. 客户端的响应速度大大变快(用户体验好): 3. 客户端的数据加载出错情况大大较少,大大提高了应有的稳定性(用户体验好): 4.

让Android Volley 支持cookie session 其实很简单!

看以下几步操作即可: 实例化带cookie DefaultHttpClient 网络通信类 /** * 返回请求队列 * @return */ private RequestQueue getRequestQueue() { if (mRequestQueue == null) { DefaultHttpClient httpclient = new DefaultHttpClient(); //非持久化存储(内存存储) BasicCookieStore | 持久化存储 PreferencesC

Android中WebView的JavaScript代码和本地代码交互的三种方式

一.Android中WebView的漏洞分析 最近在开发过程中遇到一个问题,就是WebView使用的时候,还是需要解决之前系统(4.2之前)导致的一个漏洞,虽然现在这个系统版本用户很少了,但是也不能忽视,关于这个漏洞,这里就不多做解释了,可能有的同学早就了解了,本来想写一篇文章详细介绍一下,但是网上的知识太多了,而且都很详细,就没弄了,这里大致简单明了的说几句: 第一.漏洞产生的原因 这个漏洞导致的原因主要是因为Android中WebView中的JS访问本地方法的方式存在缺陷,我们做过交互的都知