1 31 32 import java.io.IOException ; 33 34 import org.apache.commons.httpclient.Credentials; 35 import org.apache.commons.httpclient.Header; 36 import org.apache.commons.httpclient.HttpClient; 37 import org.apache.commons.httpclient.HttpException; 38 import org.apache.commons.httpclient.HttpMethod; 39 import org.apache.commons.httpclient.UsernamePasswordCredentials; 40 import org.apache.commons.httpclient.methods.GetMethod; 41 42 50 public class TrivialApp 51 { 52 53 private static final void printUsage() 54 { 55 System.out.println(); 56 System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] TrivialApp <url> [<username> <password>]"); 57 System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar"); 58 System.out.println("<loglevel> - one of error, warn, info, debug, trace"); 59 System.out.println("<url> - some valid URL"); 60 System.out.println("<username> - username for protected page"); 61 System.out.println("<password> - password for protected page"); 62 System.out.println(); 63 } 64 65 public static void main(String [] args) 66 { 67 if ((args.length != 1) && (args.length != 3)) { 68 printUsage(); 69 System.exit(-1); 70 } 71 72 Credentials creds = null; 73 if (args.length >= 3) { 74 creds = new UsernamePasswordCredentials(args[1], args[2]); 75 } 76 77 HttpClient client = new HttpClient(); 79 80 client.setConnectionTimeout(5000); 82 83 if (creds != null) { 85 client.getState().setCredentials(null, null, creds); 86 } 87 88 String url = args[0]; 89 HttpMethod method = null; 90 91 method = new GetMethod(url); 93 method.setFollowRedirects(true); 94 method.setStrictMode(false); 95 101 String responseBody = null; 103 try{ 104 client.executeMethod(method); 105 responseBody = method.getResponseBodyAsString(); 106 } catch (HttpException he) { 107 System.err.println("Http error connecting to '" + url + "'"); 108 System.err.println(he.getMessage()); 109 System.exit(-4); 110 } catch (IOException ioe){ 111 System.err.println("Unable to connect to '" + url + "'"); 112 System.exit(-3); 113 } 114 115 116 System.out.println("*** Request ***"); 118 System.out.println("Request Path: " + method.getPath()); 119 System.out.println("Request Query: " + method.getQueryString()); 120 Header[] requestHeaders = method.getRequestHeaders(); 121 for (int i=0; i<requestHeaders.length; i++){ 122 System.out.print(requestHeaders[i]); 123 } 124 125 System.out.println("*** Response ***"); 127 System.out.println("Status Line: " + method.getStatusLine()); 128 Header[] responseHeaders = method.getResponseHeaders(); 129 for (int i=0; i<responseHeaders.length; i++){ 130 System.out.print(responseHeaders[i]); 131 } 132 133 System.out.println("*** Response Body ***"); 135 System.out.println(responseBody); 136 137 method.releaseConnection(); 139 method.recycle(); 140 141 System.exit(0); 142 } 143 } 144 | Popular Tags |