How to handle cookies in Android

Source: Internet
Author: User

managing Cookies

HttpClient provides cookie management features that can is particularly useful to test the the-a application handles Cook ies. Listing 9-3 shows an example where do I HttpClient to add a cookie to a request and also to list details of the cookie set By the JSP you invoke using the HttpClient code.

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

Listing 9-3. Cookiestrial.javapackage 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 N Ame= 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.compat        ibility); 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 (). GetC        Ookies ();            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, your use of the Httpstate instance to store a new cookie and then associate this instance with Thehttpclient I Nstance. You then invoke cookiemgt.jsp. This JSP was meant to print the cookie 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 are as follows:

statusline>>>http/1.1 okcookiename=abcdvalue=00000domain=127.0.0.1cookiename=xyzvalue=12345domain= 127.0.0.1cookiename=jsessionidvalue=c46581331881a84483f0004390f94508domain=127.0.0.1

In this output, note that although the cookie named ABCD have been created from Cookiestrial, and the other cookies 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 if cookiemgt.jsp receives the request from the Cookiestrial class, the cookie NAMEDABCD is the only COO Kie that existed. The sidebar "HTTPS and Proxy Servers" shows how do you should handle requests over HTTPS and configure your client to go thro Ugh a proxy.

HTTPS and Proxy Servers

Using HttpClient to try out URLs, the involve HTTPS is the same as with ordinary URLs. Just state https://... as your URL, and it should work fine. Need to has 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 no require any separate download and Installation.

If you had 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 there is no methods and have a single implementation usernamepasswordcredentials. You can use this class to create a Credentials object, holds the username and password required for Basic Authenticati On.

You'll now see the HttpClient component's capability to use Multipartpostmethod to upload multiple files. You'll look at the tandem with the Commons FileUpload component. This Commons component are 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 are meant for use on the server side; In other words, it handles where the files is being uploaded to-not the client side where the files is uploaded from. Uploading files from an HTML form are pretty simple; However, handling these files when they get to the server are not so simple. If you want to apply any rules and the 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 a nd store them in appropriate locations. You'll now see the example where you upload some files first using a standard HTML form and then using HttpClient code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.