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的更多相关文章

  1. 【WebView】Android WebView中的Cookie操作

    Hybrid App(混合式应用)的开发过程中少不了与WebView的交互,在涉及到账户体系的产品中,包含了一种登录状态的传递.比如,在Native(原生)界面的登录操作,进入到Web界面时,涉及到账 ...

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

    [51CTO专稿]本文将具体介绍Android中的防缓冲区溢出技术的来龙去脉. 1.什么是ASLR? ASLR(Address space layout randomization)是一种针对缓冲区溢 ...

  3. Token在android中的使用

    首先Token是一个怎么样的东西,Token存在的意义又在哪里?学过php或是其他web开发的人都知道一个东西叫session和cookie,这些东西可以在服务器或是本地保存一些东西,比如说登录状态, ...

  4. Android中的HTTP通信

    前言:近期在慕课网学习了慕课网课程Android中的HTTP通信,就自己总结了一下,其中参考了不少博文,感谢大家的分享. 文章内容包括:1.HTTP简介2.HTTP/1.0和HTTP/1.1之间的区别 ...

  5. Android中事件传递机制的总结

    事件传递虽然算不上某个单独的知识点,但是在实际项目开发中肯定会碰到,如果不明白其中的原理,那在设计各种滑动效果时就会感到很困惑. 关于事件的传递,我们可能会有以下疑问: 事件是如何传递的 事件是如何处 ...

  6. Android中对Log日志文件的分析[转]

    一,Bug出现了, 需要“干掉”它 bug一听挺吓人的,但是只要你懂了,android里的bug是很好解决的,因为android里提供了LOG机制,具体的底层代码,以后在来分析,只要你会看bug, a ...

  7. 系统剖析Android中的内存泄漏

    [转发]作为Android开发人员,我们或多或少都听说过内存泄漏.那么何为内存泄漏,Android中的内存泄漏又是什么样子的呢,本文将简单概括的进行一些总结. 关于内存泄露的定义,我可以理解成这样 没 ...

  8. Android中的Intent详解

    前言: 每个应用程序都有若干个Activity组成,每一个Activity都是一个应用程序与用户进行交互的窗口,呈现不同的交互界面.因为每一个Acticity的任务不一样,所以经常互在各个Activi ...

  9. Android中的SQLite使用学习

    Android中的SQLite使用学习 SQLite是非常流行的嵌入式关系型数据库,轻载, 速度快,而且是开源.在Android中,runtime提供SQLite,所以我们可以使用SQLite,而且是 ...

随机推荐

  1. Java 8 中新的 Date 和 Time 类入门详解

    这篇文章主要是java8中新的Date和Time API的实战.新的Date和Time类是java开发者社区千呼万唤始出来的.Java8 之前存在的Date类一直都受人诟病,很多人都会选择使用第三方的 ...

  2. java—— 编译与运行

    内容:使用javac 指定编译多个目录下java文件 链接:http://zhidao.baidu.com/link?url=W5ZERu8_ouGD-L_JH0vqqawhJNitsGbonQAAT ...

  3. Hibernate 入门的第一个程序

    一. Hibernate介绍     Hibernate是基于对象/关系映射(ORM,Object/Relational Mapping)的一个解决方案.ORM方案的思想是将对象模型表示的对象映射到关 ...

  4. Android 使用 RemoteViews 发送自定义通知 ,遇到 Couldn't expand RemoteViews问题总结

    在RemoteViews这种调用方式中,你只能使用以下几种界面组件: Layout:     FrameLayout, LinearLayout, RelativeLayout Component: ...

  5. [转] 强大的python字符串解析

    1.python字符串通常有单引号('...').双引号("...").三引号("""...""")或('''...'' ...

  6. 全球最流行的66款App的共同规律

    根据苹果AppStore.Google Play.App Annie.亚马逊 AppStore及Windows Phone 应用商店历年的公开数据统计,以下66个非游戏类应用正在全球范围内流行,持续时 ...

  7. Android布局文件-错误

    View requires API level 14 (current min is 8): <?xml version="1.0" encoding="utf-8 ...

  8. 【转】Android开源项目 分类 便于查看

    之前转载了一个开源项目的文章,发现那些都是没有系统的总结,这里又转载一篇有系统总结的文章. Android开源项目系列汇总已完成,包括: Android开源项目第一篇——个性化控件(View)篇 An ...

  9. 使用SQL Server CONVERT() 函数

    语法 CONVERT(data_type(length),data_to_be_converted,style) data_type(length) 规定目标数据类型(带有可选的长度).data_to ...

  10. centos安装vim以及设置

    原文链接:http://www.xiaohuai.com/2884 Centos里的VI只默认安装了vim-minimal-7.x.所以无论是输入vi或者 vim查看文件,syntax功能都无法正常启 ...