zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Spring---------ThreadLocal(线程变量副本)
    Spring----Spring的IoC容器
    Spring----IoC Service Provieder
    三种依赖注入的方式
    数据库并发操作可能出现的问题之---更新丢失
    有状态bean与无状态bean
    Spring Data JPA、 MyBatis与Hibernate简单对比
    spring-bean的生命周期
    TCP/IP详解--拥塞控制 & 慢开始、拥塞避免、快重传和快恢复。
    如何在云服务器创建maven私有仓库
  • 原文地址:https://www.cnblogs.com/daishuguang/p/3876112.html
Copyright © 2011-2022 走看看