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.

TheHttpStateclass plays an important role while working with cookies. TheHttpStateclass 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.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 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 theHttpStateinstance to store a new cookie and then associate this instance with theHttpClientinstance. You then invokeCookieMgt.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"));%>

CAUTIONHttpClient code uses the classorg.apache.commons.httpclient.Cookie, and JSP and servlet code uses the classjavax.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 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 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 whenCookieMgt.jspreceives the request from theCookiesTrialclass, the cookie namedABCDwas 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 statehttps://…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. ReplacePROXYHOSTwith the host name and replace9999with 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 thesetProxyCredentialsmethod of the classHttpState. This method takes aCredentialsobject as a parameter.Credentialsis a marker interface that has no methods and has a single implementationUsernamePasswordCredentials. You can use this class to create aCredentialsobject 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.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. 一个登录框 + 用JS取表单中的元素
  2. JavaScript实现滑块验证案例
  3. 用python实现超强的加密软件
  4. C#中调用MySQL存储过程的方法
  5. table课程表,用户注册模板,内联框架实现后
  6. PHP方法的返回值示例详解
  7. 一个简单的留言板
  8. dom元素的增删改操作
  9. PHP中国际化的字符串排序和比较对象详解
  10. js中的firstElementChild,lastElementChil