1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/test/org/apache/commons/httpclient/TestHeaderOps.java $
3    * $Revision: 1425331 $
4    * $Date: 2012-12-22 18:29:41 +0000 (Sat, 22 Dec 2012) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  import java.net.InetAddress;
34  import java.util.Iterator;
35  
36  import junit.framework.Test;
37  import junit.framework.TestSuite;
38  
39  import org.apache.commons.httpclient.methods.GetMethod;
40  import org.apache.commons.httpclient.protocol.Protocol;
41  import org.apache.commons.httpclient.server.HttpService;
42  import org.apache.commons.httpclient.server.SimpleRequest;
43  import org.apache.commons.httpclient.server.SimpleResponse;
44  
45  /***
46   * @author Rodney Waldhoff
47   * @version $Id: TestHeaderOps.java 480424 2006-11-29 05:56:49Z bayard $
48   */
49  public class TestHeaderOps extends HttpClientTestBase {
50  
51      public TestHeaderOps(String testName) throws Exception {
52          super(testName);
53      }
54  
55      public static Test suite() {
56          TestSuite suite = new TestSuite(TestHeaderOps.class);
57          return suite;
58      }
59  
60      public static void main(String args[]) {
61          String[] testCaseName = { TestHeaderOps.class.getName() };
62          junit.textui.TestRunner.main(testCaseName);
63      }
64  
65      // ------------------------------------------------------------------ Tests
66  
67      class HeaderDumpService implements HttpService {
68  
69          public HeaderDumpService() {
70              super();
71          }
72  
73          public boolean process(final SimpleRequest request, final SimpleResponse response)
74              throws IOException
75          {
76              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
77              response.setStatusLine(httpversion, HttpStatus.SC_OK);
78              response.addHeader(new Header("Content-Type", "text/plain"));            
79              response.addHeader(new Header("HeaderSetByServlet", "Yes"));            
80  
81              StringBuffer buffer = new StringBuffer(); 
82              buffer.append("Request headers: \r\n");
83              for (Iterator i = request.getHeaderIterator(); i.hasNext(); ) {
84                  Header header = (Header) i.next();
85                  buffer.append("name=\"");
86                  buffer.append(header.getName().toLowerCase());
87                  buffer.append("\";value=\"");
88                  buffer.append(header.getValue());
89                  buffer.append("\"\r\n");
90              }
91              response.setBodyString(buffer.toString());
92              return true;
93          }
94      }
95  
96      /***
97       * Test {@link HttpMethod#addRequestHeader}.
98       */
99      public void testAddRequestHeader() throws Exception {
100         this.server.setHttpService(new HeaderDumpService());
101         
102         GetMethod method = new GetMethod("/");
103         method.setRequestHeader(new Header("addRequestHeader(Header)","True"));
104         method.setRequestHeader("addRequestHeader(String,String)","Also True");
105         try {
106             this.client.executeMethod(method);
107             String s = method.getResponseBodyAsString();
108             assertTrue(s.indexOf("name=\"addrequestheader(header)\";value=\"True\"") >= 0);
109             assertTrue(s.indexOf("name=\"addrequestheader(string,string)\";value=\"Also True\"") >= 0);
110         } finally {
111             method.releaseConnection();
112         }
113     }
114 
115     /***
116      * Test {@link HttpMethod#removeRequestHeader}.
117      */
118     public void testRemoveRequestHeader() throws Exception {
119         this.server.setHttpService(new HeaderDumpService());
120         
121         GetMethod method = new GetMethod("/");
122         method.setRequestHeader(new Header("XXX-A-HEADER","true"));
123         method.removeRequestHeader("XXX-A-HEADER");
124         
125         try {
126             this.client.executeMethod(method);
127             String s = method.getResponseBodyAsString();
128             assertTrue(!(s.indexOf("xxx-a-header") >= 0));
129         } finally {
130             method.releaseConnection();
131         }
132     }
133 
134     /***
135      * Test {@link HttpMethod#setRequestHeader}.
136      */
137     public void testOverwriteRequestHeader() throws Exception {
138         this.server.setHttpService(new HeaderDumpService());
139         
140         GetMethod method = new GetMethod("/");
141         method.setRequestHeader(new Header("xxx-a-header","one"));
142         method.setRequestHeader("XXX-A-HEADER","two");
143         
144         try {
145             this.client.executeMethod(method);
146             String s = method.getResponseBodyAsString();
147             assertTrue(s.indexOf("name=\"xxx-a-header\";value=\"two\"") >= 0);
148         } finally {
149             method.releaseConnection();
150         }
151     }
152 
153     /***
154      * Test {@link HttpMethod#getResponseHeader}.
155      */
156     public void testGetResponseHeader() throws Exception {
157         this.server.setHttpService(new HeaderDumpService());
158         
159         GetMethod method = new GetMethod("/");
160         try {
161             this.client.executeMethod(method);
162             Header h = new Header("HeaderSetByServlet","Yes");
163             assertEquals(h, method.getResponseHeader("headersetbyservlet"));
164         } finally {
165             method.releaseConnection();
166         }
167     }
168 
169     /***
170      * Test {@link HttpMethodBase.addHostRequestHeader}.
171      */
172     public void testHostRequestHeader() throws Exception {
173         this.server.setHttpService(new HeaderDumpService());
174 
175         String hostname = this.server.getLocalAddress();
176         int port = this.server.getLocalPort();
177         
178         InetAddress addr = InetAddress.getByName(hostname);
179         String ip = addr.getHostAddress();
180 
181         GetMethod get = new GetMethod("/");
182 
183         // Open connection using IP.  Host header should be sent
184         // Note: RFC 2616 is somewhat unclear on whether a host should
185         // be sent in this context - however, both Mozilla and IE send
186         // the header for an IP address, instead of sending blank.
187         this.client.getHostConfiguration().setHost(ip, port);
188         try {
189             this.client.executeMethod(get);
190             Header hostHeader = get.getRequestHeader("Host");
191             assertTrue(hostHeader != null);
192             if (port == Protocol.getProtocol("http").getDefaultPort()) {
193                 // no port information should be in the value
194                 assertTrue(hostHeader.getValue().equals(ip));
195             } else {
196                 assertTrue(hostHeader.getValue().equals(ip + ":" + port));
197             }
198         } finally {
199             get.releaseConnection();
200         }
201 
202         get = new GetMethod("/");
203         // Open connection using Host.  Host header should
204         // contain this value (this test will fail if DNS
205         // is not available. Additionally, if the port is
206         // something other that 80, then the port value
207         // should also be present in the header.
208         this.client.getHostConfiguration().setHost(hostname, port);
209         try {
210             this.client.executeMethod(get);
211             Header hostHeader = get.getRequestHeader("Host");
212             assertTrue(hostHeader != null);
213             if (port == Protocol.getProtocol("http").getDefaultPort()) {
214                 // no port information should be in the value
215                 assertTrue(hostHeader.getValue().equals(hostname));
216             } else {
217                 assertTrue(hostHeader.getValue().equals(hostname + ":" + port));
218             }
219         } finally {
220             get.releaseConnection();
221         }
222     }
223 }
224