1 /* 2 * Copyright 2000-2004 The Apache Software Foundation. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package org.apache.commons.scaffold.http; 18 19 import java.net.*; 20 import java.io.*; 21 22 23 /** 24 * A network client that reads from a HTTP URL. 25 * <P> 26 * Taken from Core Servlets and JavaServer Pages 27 * from Prentice Hall and Sun Microsystems Press, 28 * http://www.coreservlets.com/. 29 * © 2000 Marty Hall; may be freely used or adapted. 30 * <P> 31 * Adapted for general use by a servlet to read a page 32 * into a StringBuffer by Ted Husted, August 2001. 33 * 34 * @author Marty Hall 35 * @author Ted Husted 36 * @version $Revision: 155464 $ $Date: 2005-02-26 13:26:54 +0000 (Sat, 26 Feb 2005) $ 37 */ 38 public class HttpClient { 39 40 /** 41 * Retrieve indicated page, returning headers and 42 * page content. 43 * 44 * @param host 45 * @param port 46 * @param requestLine 47 * @param requestHeaders 48 * @param content 49 * @exception Catches IOException and UnknownHostException, 50 * and returns messages in content. 51 * @author Marty Hall 52 * @author Ted Husted 53 * @version $Revision: 155464 $ $Date: 2005-02-26 13:26:54 +0000 (Sat, 26 Feb 2005) $ 54 */ 55 public HttpClient( 56 String host, int port, 57 String requestLine, String[] requestHeaders, 58 StringBuffer responseHeaders, StringBuffer responseContent) 59 throws UnknownHostException,IOException { 60 61 // check host and connect - Will succeed or throw UHE 62 InetAddress.getByName(host); 63 Socket uriSocket = new Socket(host,port); 64 65 // handleConnection - May throw IOE 66 PrintWriter out = SocketUtil.getWriter(uriSocket); 67 BufferedReader in = SocketUtil.getReader(uriSocket); 68 69 // say howdy 70 out.println(requestLine); 71 72 // send any headers, and then blank 73 for(int i=0; i<requestHeaders.length; i++) { 74 if (requestHeaders[i] == null) 75 break; 76 else 77 out.println(requestHeaders[i]); 78 } 79 out.println(); 80 81 // capture response 82 String line; 83 // - headers 84 while ((line = in.readLine()) != null) { 85 responseHeaders.append(line + "\n"); 86 if ("".equals(line)) break; 87 } 88 // - content 89 while ((line = in.readLine()) != null) 90 responseContent.append(line + "\n"); 91 } 92 }