1 30 31 import org.apache.commons.httpclient.HttpConnection; 32 import org.apache.commons.httpclient.HttpState; 33 import org.apache.commons.httpclient.HttpStatus; 34 import org.apache.commons.httpclient.HttpMethod; 35 import org.apache.commons.httpclient.URI; 36 import org.apache.commons.httpclient.UsernamePasswordCredentials; 37 import org.apache.commons.httpclient.protocol.Protocol; 38 import org.apache.commons.httpclient.methods.GetMethod; 39 import org.apache.commons.httpclient.ConnectMethod; 40 41 48 49 public class CustomHttpConnection 50 { 51 public static void main(String [] args) throws Exception 52 { 53 if (args.length != 1) 54 { 55 System.err.println("Usage: java CustomHttpConnection <url>"); 56 System.err.println("<url> The url of a webpage"); 57 System.exit(1); 58 } 59 60 URI uri = new URI(args[0].toCharArray()); 62 String schema = uri.getScheme(); 63 if ((schema == null) || (schema.equals(""))) 64 { 65 schema = "http"; 66 } 67 Protocol protocol = Protocol.getProtocol(schema); 68 69 HttpState state = new HttpState(); 70 71 HttpMethod method = new GetMethod(uri.toString()); 72 String host = uri.getHost(); 73 int port = uri.getPort(); 74 75 HttpConnection connection = new HttpConnection(host, port, protocol); 76 77 connection.setProxyHost(System.getProperty("http.proxyHost")); 78 connection.setProxyPort( Integer.parseInt(System.getProperty("http.proxyPort","80"))); 79 80 if (System.getProperty("http.proxyUserName") != null) 81 { 82 state.setProxyCredentials(null, null, 83 new UsernamePasswordCredentials( 84 System.getProperty("http.proxyUserName"), 85 System.getProperty("http.proxyPassword"))); 86 } 87 88 if (connection.isProxied() && connection.isSecure()) { 89 method = new ConnectMethod(method); 90 } 91 method.execute(state, connection); 92 93 if (method.getStatusCode() == HttpStatus.SC_OK) { 94 System.out.println(method.getResponseBodyAsString()); 95 } else { 96 System.out.println("Unexpected failure: " + method.getStatusLine().toString()); 97 } 98 method.releaseConnection(); 99 } 100 } 101 | Popular Tags |