Hi,

Attached is a patch to correct the
HttpMethodBase.addHostRequestHeader().

Currently, this method only adds the hostname to the header value, 
however, if the target service is on a different port, then the
header provided will be incorrect.

The patch also includes some general formatting cleanup to the
class.

-rl




Index: HttpMethodBase.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v
retrieving revision 1.28
diff -u -r1.28 HttpMethodBase.java
--- HttpMethodBase.java	16 Apr 2002 14:30:42 -0000	1.28
+++ HttpMethodBase.java	4 Jun 2002 17:13:11 -0000
@@ -164,7 +164,8 @@
      * in the same way that most Http user agent's do (and many HTTP servers
      * expect.
      *
-     * NOTE:  StrictMode is currently experimental and its functionlaity may change in the future.
+     * NOTE:  StrictMode is currently experimental and its functionlaity 
+     *        may change in the future.
      *
      */
     public void setStrictMode(boolean strictMode)
@@ -175,7 +176,8 @@
     /**
      * Returns the value of strictMode.
      *
-     * NOTE:  StrictMode is currently experimental and its functionlaity may change in the future.
+     * NOTE:  StrictMode is currently experimental and its functionlaity 
+     *        may change in the future.
      *
      * @return true if strict mode is enabled.
      */
@@ -193,7 +195,7 @@
      */
     public void setRequestHeader(String headerName, String headerValue) {
         Header header = new Header(headerName, headerValue);
-        requestHeaders.put(headerName.toLowerCase(),header);
+        requestHeaders.put(headerName.toLowerCase(), header);
     }
 
     /**
@@ -203,7 +205,7 @@
      * @param header the header
      */
     public void setRequestHeader(Header header) {
-        requestHeaders.put(header.getName().toLowerCase(),header);
+        requestHeaders.put(header.getName().toLowerCase(), header);
     }
 
     /**
@@ -223,11 +225,10 @@
         if (null == header) {
             header = new Header(headerName, headerValue);
         } else {
-            header.setValue( (null == header.getValue() ? "" : header.getValue()) +
-                             ", " +
-                             (null == headerValue ? "" : headerValue));
+            header.setValue((null == header.getValue() ? "" : header.getValue()) +
+                             ", " + (null == headerValue ? "" : headerValue));
         }
-        requestHeaders.put(headerName.toLowerCase(),header);
+        requestHeaders.put(headerName.toLowerCase(), header);
     }
 
     /**
@@ -242,15 +243,15 @@
         // semantics of the message, by appending each subsequent field-value
         // to the first, each separated by a comma."
         //   - HTTP/1.0 (4.3)
-        Header orig = (Header)(requestHeaders.get(header.getName().toLowerCase()));
+        Header orig = (Header) requestHeaders.get(header.getName().toLowerCase());
         if (null == orig) {
             orig = header;
         } else {
-            orig.setValue( (null == orig.getValue() ? "" : orig.getValue()) +
+            orig.setValue((null == orig.getValue() ? "" : orig.getValue()) +
                            ", " +
                            (null == header.getValue() ? "" : header.getValue()));
         }
-        requestHeaders.put(orig.getName().toLowerCase(),orig);
+        requestHeaders.put(orig.getName().toLowerCase(), orig);
     }
 
     /**
@@ -306,9 +307,9 @@
     public void setQueryString(NameValuePair[] params) {
         StringBuffer buf = new StringBuffer();
         boolean needAmp = false;
-        for(int i=0;i<params.length;i++) {
+        for (int i = 0; i < params.length; i++) {
             if (needAmp) {
-                buf.append("&");
+                buf.append('&');
             } else {
                 needAmp = true;
             }
@@ -316,7 +317,7 @@
                 buf.append(URIUtil.encode(params[i].getName()));
             }
             if (null != params[i].getValue()) {
-                buf.append("=");
+                buf.append('=');
                 buf.append(URIUtil.encode(params[i].getValue()));
             }
         }
@@ -334,7 +335,7 @@
      * Return an array of my request headers.
      */
     public Header[] getRequestHeaders() {
-        return (Header[])(requestHeaders.values().toArray(new Header[requestHeaders.size()]));
+        return (Header[]) requestHeaders.values().toArray(new Header[requestHeaders.size()]);
     }
 
     // ---------------------------------------------------------------- Queries
@@ -367,7 +368,7 @@
      * Return an array my response headers.
      */
     public Header[] getResponseHeaders() {
-        return (Header[])(responseHeaders.values().toArray(new Header[responseHeaders.size()]));
+        return (Header[]) responseHeaders.values().toArray(new Header[responseHeaders.size()]);
     }
 
     /**
@@ -409,7 +410,7 @@
      * but not recycled.
      */
     public boolean hasBeenUsed() {
-       return used;
+        return used;
     }
 
 
@@ -451,14 +452,14 @@
         Set visited = new HashSet();
         Set realms = new HashSet();
         int retryCount = 0;
-        for(;;) {
-            visited.add(connection.getHost() + ":" + connection.getPort() + "|" + HttpMethodBase.generateRequestLine(connection, getName(),getPath(),getQueryString(),(http11 ? "HTTP/1.1" : "HTTP/1.0")));
+        for (;;) {
+            visited.add(connection.getHost() + ':' + connection.getPort() + '|' + HttpMethodBase.generateRequestLine(connection, getName(), getPath(), getQueryString(), (http11 ? "HTTP/1.1" : "HTTP/1.0")));
 
             if (log.isDebugEnabled()) {
                 log.debug("HttpMethodBase.execute(): looping.");
             }
 
-            try{
+            try {
                 if (!connection.isOpen()) {
                     if (log.isDebugEnabled()) {
                         log.debug("HttpMethodBase.execute(): opening connection.");
@@ -466,13 +467,13 @@
                     connection.open();
                 }
 
-                writeRequest(state,connection);
+                writeRequest(state, connection);
                 used = true;
 
                 // need to close output?, but when?
-                readResponse(state,connection);
-            }catch(HttpRecoverableException e){
-                if(retryCount >= maxRetries){
+                readResponse(state, connection);
+            } catch (HttpRecoverableException e) {
+                if (retryCount >= maxRetries) {
                     throw new HttpException(e.toString());
                 }
                 retryCount++;
@@ -482,12 +483,12 @@
             }
             if (HttpStatus.SC_CONTINUE == statusCode) {
                 if (!bodySent) {
-                    bodySent = writeRequestBody(state,connection);
+                    bodySent = writeRequestBody(state, connection);
                 } else {
                     log.warn("HttpMethodBase.execute(): received 100 response, but I've already sent the response.");
                     // According to RFC 2616 this respose should be ignored
                 }
-                readResponse(state,connection);
+                readResponse(state, connection);
             }
 
             if (!http11) {
@@ -520,8 +521,8 @@
 
                     boolean authenticated = false;
                     try {
-                        authenticated = Authenticator.authenticate(this,state);
-                    } catch(HttpException e) {
+                        authenticated = Authenticator.authenticate(this, state);
+                    } catch (HttpException e) {
                         // ignored
                     }
                     if (!authenticated) {
@@ -567,8 +568,8 @@
                                 if (-1 == port) {
                                     port = connection.isSecure() ? 443 : 80;
                                 }
-                                url = new URL(protocol,connection.getHost(),port,location.getValue());                                
-                            } else if(!isStrictMode() && location.getValue().indexOf("://") < 0) {
+                                url = new URL(protocol, connection.getHost(), port, location.getValue());                                
+                            } else if (!isStrictMode() && location.getValue().indexOf("://") < 0) {
                                 /*
                                  * Location doesn't start with / but it doesn't contain a protocol.
                                  * Per RFC 2616, that's an error.  In non-strict mode we'll try
@@ -576,16 +577,16 @@
                                  */
                                 String protocol = connection.isSecure() ? "https" : "http";
                                 int port = connection.getPort();
-                                if(-1 == port) {
+                                if (-1 == port) {
                                     port = connection.isSecure() ? 443 : 80;
                                 }
-                                URL currentUrl = new URL(protocol,connection.getHost(),port,getPath());
+                                URL currentUrl = new URL(protocol, connection.getHost(), port, getPath());
                                 url = new URL(currentUrl, location.getValue());
                             } else {
                                 url = new URL(location.getValue());
                             }                            
-                        } catch(MalformedURLException e) {
-                            log.error("Exception while parsing location header \"" + location + "\"",e);
+                        } catch (MalformedURLException e) {
+                            log.error("Exception while parsing location header \"" + location + "\"", e);
                             throw new HttpException(e.toString());
                         }
                         if ("http".equalsIgnoreCase(url.getProtocol())) {
@@ -623,7 +624,7 @@
                         String qs = URIUtil.getQueryString(url.toString());
 
                         // if we haven't already, let's try it again with the new path
-                        if (visited.contains(connection.getHost() + ":" + connection.getPort() + "|" + HttpMethodBase.generateRequestLine(connection, getName(),absolutePath,qs,(http11 ? "HTTP/1.1" : "HTTP/1.0")))) {
+                        if (visited.contains(connection.getHost() + ":" + connection.getPort() + "|" + HttpMethodBase.generateRequestLine(connection, getName(), absolutePath, qs, (http11 ? "HTTP/1.1" : "HTTP/1.0")))) {
                             throw new HttpException("Redirect going into a loop, visited \"" + absolutePath + "\" already.");
                         } else {
                             if (log.isDebugEnabled()) {
@@ -687,12 +688,12 @@
      */
     protected void writeRequest(HttpState state, HttpConnection conn) throws IOException, HttpException {
         if (log.isDebugEnabled()) {
-       		log.debug("HttpMethodBase.writeRequest(HttpState,HttpConnection)");
+       		log.debug("HttpMethodBase.writeRequest(HttpState, HttpConnection)");
         }
-        writeRequestLine(state,conn);
-        writeRequestHeaders(state,conn);
+        writeRequestLine(state, conn);
+        writeRequestHeaders(state, conn);
         conn.writeLine(); // close head
-        bodySent = writeRequestBody(state,conn);
+        bodySent = writeRequestBody(state, conn);
     }
 
 
@@ -709,9 +710,9 @@
      */
     protected void writeRequestLine(HttpState state, HttpConnection conn) throws IOException, HttpException {
         if (log.isDebugEnabled()) {
-        	log.debug("HttpMethodBase.writeRequestLine(HttpState,HttpConnection)");
+        	log.debug("HttpMethodBase.writeRequestLine(HttpState, HttpConnection)");
         }
-        String requestLine = HttpMethodBase.generateRequestLine(conn, getName(),getPath(),getQueryString(),(http11 ? "HTTP/1.1" : "HTTP/1.0"));
+        String requestLine = HttpMethodBase.generateRequestLine(conn, getName(), getPath(), getQueryString(), (http11 ? "HTTP/1.1" : "HTTP/1.0"));
         conn.print(requestLine);
     }
 
@@ -733,11 +734,11 @@
      */
     protected void writeRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException {
         if (log.isDebugEnabled()) {
-        	log.debug("HttpMethodBase.writeRequestHeaders(HttpState,HttpConnection)");
+        	log.debug("HttpMethodBase.writeRequestHeaders(HttpState, HttpConnection)");
         }
-        addRequestHeaders(state,conn);
+        addRequestHeaders(state, conn);
         Iterator it = requestHeaders.values().iterator();
-        while(it.hasNext()) {
+        while (it.hasNext()) {
             conn.print(((Header)it.next()).toExternalForm());
         }
     }
@@ -763,11 +764,11 @@
      * @param conn the {@link HttpConnection} the headers will eventually be written to
      */
     protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException {
-        addUserAgentRequestHeader(state,conn);
-        addHostRequestHeader(state,conn);
-        addCookieRequestHeader(state,conn);
-        addAuthorizationRequestHeader(state,conn);
-        addContentLengthRequestHeader(state,conn);
+        addUserAgentRequestHeader(state, conn);
+        addHostRequestHeader(state, conn);
+        addCookieRequestHeader(state, conn);
+        addAuthorizationRequestHeader(state, conn);
+        addContentLengthRequestHeader(state, conn);
     }
 
     /**
@@ -789,7 +790,12 @@
     protected void addHostRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException {
         // add host (should do this conditionally?, i.e., don't send to http/1.0?)
         if (!requestHeaders.containsKey("host")) {
-            setRequestHeader("Host",conn.getHost());
+            int port = conn.getPort();
+            if (port != 80) {
+                setRequestHeader("Host", conn.getHost() + ':' + port);
+            } else {
+                setRequestHeader("Host", conn.getHost());
+            }
         }
     }
 
@@ -798,7 +804,7 @@
      */
     protected void addCookieRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException {
         Header cookieHeader = Cookie.createCookieHeader(conn.getHost(), conn.getPort(), getPath(), conn.isSecure(), new Date(), state.getCookies());
-        if(null != cookieHeader) {
+        if (null != cookieHeader) {
             setRequestHeader(cookieHeader);
         }
     }
@@ -814,8 +820,8 @@
             Header wwwAuthenticateHeader = (Header)(responseHeaders.get("www-authenticate"));
             if (null != wwwAuthenticateHeader) {
                 try {
-                    Authenticator.authenticate(this,state);
-                } catch(HttpException e) {
+                    Authenticator.authenticate(this, state);
+                } catch (HttpException e) {
                     // ignored
                 }
             }
@@ -833,9 +839,9 @@
         int len = getRequestContentLength();
         if (!requestHeaders.containsKey("content-length")) {
             if (0 < len) {
-                setRequestHeader("Content-Length",String.valueOf(len));
+                setRequestHeader("Content-Length", String.valueOf(len));
             } else if (http11 && (len < 0)) {
-                setRequestHeader("Transfer-Encoding","chunked");
+                setRequestHeader("Transfer-Encoding", "chunked");
             }
         }
     }
@@ -916,14 +922,14 @@
      */
     protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException {
         if (log.isDebugEnabled()) {
-        	log.debug("HttpMethodBase.readResponse(HttpState,HttpConnection)");
+        	log.debug("HttpMethodBase.readResponse(HttpState, HttpConnection)");
         }
-        readStatusLine(state,conn);
-        processStatusLine(state,conn);
-        readResponseHeaders(state,conn);
-        processResponseHeaders(state,conn);
-        readResponseBody(state,conn);
-        processResponseBody(state,conn);
+        readStatusLine(state, conn);
+        processStatusLine(state, conn);
+        readResponseHeaders(state, conn);
+        processResponseHeaders(state, conn);
+        readResponseBody(state, conn);
+        processResponseBody(state, conn);
     }
 
     /**
@@ -942,14 +948,14 @@
      */
     protected void readStatusLine(HttpState state, HttpConnection conn) throws IOException, HttpException {
         if (log.isDebugEnabled()) {
-        	log.debug("HttpMethodBase.readStatusLine(HttpState,HttpConnection)");
+        	log.debug("HttpMethodBase.readStatusLine(HttpState, HttpConnection)");
         }
         statusCode = -1;
         statusText = null;
 
         String statusLine = conn.readLine();
 
-        while(statusLine != null && !statusLine.startsWith("HTTP/")) {
+        while (statusLine != null && !statusLine.startsWith("HTTP/")) {
             statusLine = conn.readLine();
         }
         if (statusLine == null) {
@@ -1032,7 +1038,7 @@
         }
         responseHeaders.clear();
 
-        for(;;) {
+        for (;;) {
             String line = conn.readLine();
             if ((line == null) || (line.length() < 1)) {
                 break;
@@ -1052,9 +1058,9 @@
             } else {
                 String oldvalue =  header.getValue();
                 if (null != oldvalue) {
-                    header = new Header(name,oldvalue + ", " + value);
+                    header = new Header(name, oldvalue + ", " + value);
                 } else {
-                    header = new Header(name,value);
+                    header = new Header(name, value);
                 }
             }
             responseHeaders.put(match, header);
@@ -1087,7 +1093,7 @@
         // add cookies, if any
         // should we set cookies?
         Header setCookieHeader = getResponseHeader("set-cookie2");
-        if (null == setCookieHeader) { //ignore old-style if new is supported
+        if (null == setCookieHeader) { // ignore old-style if new is supported
             setCookieHeader = getResponseHeader("set-cookie");
         }
 
@@ -1096,7 +1102,7 @@
                 Cookie[] cookies = Cookie.parse(conn.getHost(), conn.getPort(), getPath(), conn.isSecure(), setCookieHeader);
                 state.addCookies(cookies);
             } catch (Exception e) {
-                log.error("processResponseHeaders(HttpState,HttpConnection)",e);
+                log.error("processResponseHeaders(HttpState, HttpConnection)", e);
             }
         }
     }
@@ -1159,14 +1165,14 @@
             if (null != lengthHeader) {
                 try {
                     expectedLength = Integer.parseInt(lengthHeader.getValue());
-                } catch(NumberFormatException e) {
+                } catch (NumberFormatException e) {
                     // ignored
                 }
             } else if (null != transferEncodingHeader) {
                 if ("chunked".equalsIgnoreCase(transferEncodingHeader.getValue())) {
                     expectedLength = -1;
                 }
-            } else if(canResponseHaveBody(statusCode)){
+            } else if (canResponseHaveBody(statusCode)) {
                 /*
                  * According to the specification, a response with neither Content-Length
                  * nor Transfer-Encoding indicates that the response has no body.  In
@@ -1180,7 +1186,7 @@
         InputStream is = conn.getResponseInputStream(this);
         byte[] buffer = new byte[4096];
         int nb = 0;
-        while(expectedLength == -1 || foundLength < expectedLength) {
+        while (expectedLength == -1 || foundLength < expectedLength) {
             nb = is.read(buffer);
             if (nb == -1) {
                 break;
@@ -1287,7 +1293,7 @@
      */
     protected static String generateRequestLine(HttpConnection connection, String name, String reqPath, String qString, String protocol) {
         StringBuffer buf = new StringBuffer();
-        buf.append(null == reqPath ? "/" : URIUtil.encode(reqPath,URIUtil.pathSafe()));
+        buf.append(null == reqPath ? "/" : URIUtil.encode(reqPath, URIUtil.pathSafe()));
         if (null != qString) {
             if (qString.indexOf("?") < 0) {
                 buf.append("?");
@@ -1302,7 +1308,7 @@
                 return (name +
                        " https://"; +
                        connection.getHost() +
-                       ((443 == connection.getPort() || -1 == connection.getPort()) ? "" : (":" + connection.getPort()) ) +
+                       ((443 == connection.getPort() || -1 == connection.getPort()) ? "" : (":" + connection.getPort())) +
                        buf.toString() +
                        " " +
                        protocol +
@@ -1311,7 +1317,7 @@
                 return (name +
                        " http://"; +
                        connection.getHost() +
-                       ((80 == connection.getPort() || -1 == connection.getPort()) ? "" : (":" + connection.getPort()) ) +
+                       ((80 == connection.getPort() || -1 == connection.getPort()) ? "" : (":" + connection.getPort())) +
                        buf.toString() +
                        " " +
                        protocol +
@@ -1331,9 +1337,9 @@
     {
         boolean result = true;
 
-        if((status >= 100 && status <= 199) ||    // 1XX
+        if ((status >= 100 && status <= 199) ||   // 1XX
            status == 204 ||                       // NO CONTENT
-           status == 304){                        // NOT MODIFIED
+           status == 304) {                       // NOT MODIFIED
             result = false;
         }
 

--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to