List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine
public abstract StatusLine getStatusLine();
From source file:Correct.java
public static void main(String[] args) { String URLL = ""; HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(URLL); method.setDoAuthentication(true);/*from w w w.j av a 2s.com*/ HostConfiguration hostConfig = client.getHostConfiguration(); hostConfig.setHost("172.29.38.8"); hostConfig.setProxy("172.29.90.4", 8); // NTCredentials proxyCredentials = new NTCredentials("", "", "", ""); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", "")); //// try { //// URL url = new URL(""); //// HttpURLConnection urls = (HttpURLConnection) url.openConnection(); //// //// //// } catch (MalformedURLException ex) { //// Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex); //// } catch (IOException ex) { //// Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex); //// } try { // send the transaction client.executeMethod(hostConfig, method); StatusLine status = method.getStatusLine(); if (status != null && method.getStatusCode() == 200) { System.out.println(method.getResponseBodyAsString() + "\n Status code : " + status); } else { System.err.println(method.getStatusLine() + "\n: Posting Failed !"); } } catch (IOException ioe) { ioe.printStackTrace(); } method.releaseConnection(); }
From source file:TrivialApp.java
public static void main(String[] args) { if ((args.length != 1) && (args.length != 3)) { printUsage();// w ww .j a v a2 s. c o m System.exit(-1); } Credentials creds = null; if (args.length >= 3) { creds = new UsernamePasswordCredentials(args[1], args[2]); } //create a singular HttpClient object HttpClient client = new HttpClient(); //establish a connection within 5 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //set the default credentials if (creds != null) { client.getState().setCredentials(AuthScope.ANY, creds); } String url = args[0]; HttpMethod method = null; //create a method object method = new GetMethod(url); method.setFollowRedirects(true); //} catch (MalformedURLException murle) { // System.out.println("<url> argument '" + url // + "' is not a valid URL"); // System.exit(-2); //} //execute the method String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (HttpException he) { System.err.println("Http error connecting to '" + url + "'"); System.err.println(he.getMessage()); System.exit(-4); } catch (IOException ioe) { System.err.println("Unable to connect to '" + url + "'"); System.exit(-3); } //write out the request headers System.out.println("*** Request ***"); System.out.println("Request Path: " + method.getPath()); System.out.println("Request Query: " + method.getQueryString()); Header[] requestHeaders = method.getRequestHeaders(); for (int i = 0; i < requestHeaders.length; i++) { System.out.print(requestHeaders[i]); } //write out the response headers System.out.println("*** Response ***"); System.out.println("Status Line: " + method.getStatusLine()); Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { System.out.print(responseHeaders[i]); } //write out the response body System.out.println("*** Response Body ***"); System.out.println(responseBody); //clean up the connection resources method.releaseConnection(); System.exit(0); }
From source file:ExampleP2PHttpClient.java
public static void main(String[] args) { // initialize JXTA try {/*ww w . j ava 2 s. co m*/ // sign in and initialize the JXTA network; profile this peer and create it // if it doesn't exist P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // register the P2P socket protocol factory Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80); Protocol.registerProtocol("p2phttp", jxtaHttp); //create a singular HttpClient object HttpClient client = new HttpClient(); //establish a connection within 50 seconds client.setConnectionTimeout(50000); String url = System.getProperty("url"); if (url == null || url.equals("")) { System.out.println("You must provide a URL to access. For example:"); System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo"); System.exit(1); } System.out.println("Connecting to " + url + "..."); HttpMethod method = null; //create a method object method = new GetMethod(url); method.setFollowRedirects(true); method.setStrictMode(false); //} catch (MalformedURLException murle) { // System.out.println("<url> argument '" + url // + "' is not a valid URL"); // System.exit(-2); //} //execute the method String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (HttpException he) { System.err.println("Http error connecting to '" + url + "'"); System.err.println(he.getMessage()); System.exit(-4); } catch (IOException ioe) { System.err.println("Unable to connect to '" + url + "'"); System.exit(-3); } //write out the request headers System.out.println("*** Request ***"); System.out.println("Request Path: " + method.getPath()); System.out.println("Request Query: " + method.getQueryString()); Header[] requestHeaders = method.getRequestHeaders(); for (int i = 0; i < requestHeaders.length; i++) { System.out.print(requestHeaders[i]); } //write out the response headers System.out.println("*** Response ***"); System.out.println("Status Line: " + method.getStatusLine()); Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { System.out.print(responseHeaders[i]); } //write out the response body System.out.println("*** Response Body ***"); System.out.println(responseBody); //clean up the connection resources method.releaseConnection(); method.recycle(); System.exit(0); }
From source file:com.jaspersoft.studio.server.util.HttpUtils31.java
public static HttpMethod get(HttpClient client, String url) throws HttpException, IOException { HttpMethod method = new GetMethod(url); method.setRequestHeader("Accept", "application/json"); System.out.println(method.getURI()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) System.err.println("Method failed: " + method.getStatusLine()); return method; }
From source file:fr.matriciel.AnnotationClient.java
public static String request(HttpMethod method) throws AnnotationException { String response = null;/* ww w . j a v a2 s. com*/ // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. // Deal with the response. // Use caution: ensure correct character encoding and is not binary data response = new String(responseBody); } catch (HttpException e) { throw new AnnotationException("Protocol error executing HTTP request.", e); } catch (IOException e) { throw new AnnotationException("Transport error executing HTTP request.", e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:mesquite.tol.lib.BaseHttpRequestMaker.java
protected static boolean executeMethod(HttpClient client, HttpMethod method, StringBuffer response) { boolean success = true; try {// w w w . j a va 2 s.co m // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); if (response != null) response.append(new String(responseBody)); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { // System.err.println("Fatal protocol violation: " + e.getMessage()); // e.printStackTrace(); success = false; } catch (IOException e) { // System.err.println("Fatal transport error: " + e.getMessage()); // e.printStackTrace(); success = false; } finally { // Release the connection. method.releaseConnection(); } return success; }
From source file:com.wafersystems.util.HttpUtil.java
/** * URL?/*from ww w. j av a 2 s .c o m*/ * * @param hClient HttpClient * @param url URL * * @return * @throws Exception */ public static String openURL(HttpClient hClient, String url) throws Exception { HttpMethod method = null; try { //Get method = new GetMethod(url); // URL int result = hClient.executeMethod(method); //cookie? //getCookie(method.getURI().getHost(), method.getURI().getPort(), "/" , false , hClient.getState().getCookies()); //??? result = checkRedirect(method.getURI().getHost(), method.getURI().getPort(), hClient, method, result); if (result != HttpStatus.SC_OK) logger.error(method.getPath() + "" + method.getStatusLine().toString() + "\r\n" + method.getResponseBodyAsString()); return method.getResponseBodyAsString(); } finally { method.releaseConnection(); } }
From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java
private static int executeHttpMethod(HttpMethod method) throws Exception { HttpClient client = new HttpClient(); int statusCode; try {/*from w w w . j a v a 2s .c o m*/ statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { JSONObject result = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); if (result.has("error-code")) { String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"), result.getString("stacktrace") }; throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: " + method.getStatusLine() + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]); } } return statusCode; } catch (Exception e) { throw e; } finally { method.releaseConnection(); } }
From source file:com.intellij.coldFusion.mxunit.CfmlUnitRemoteTestsRunner.java
public static void executeScript(final CfmlUnitRunnerParameters params, final ProcessHandler processHandler/*final String webPath, final String componentFilePath, final String methodName, final ProcessHandler processHandler*/, final Project project) throws ExecutionException { final Ref<ExecutionException> ref = new Ref<>(); ApplicationManager.getApplication().assertIsDispatchThread(); ApplicationManager.getApplication().executeOnPooledThread(() -> { try {//from w ww. j a v a 2 s . co m final VirtualFile componentFile = LocalFileSystem.getInstance() .refreshAndFindFileByPath(params.getPath()); if (componentFile == null) { throw new ExecutionException("File " + params.getPath() + " not found"); } // creating script files final VirtualFile directory = componentFile.getParent(); final String launcherFileName = "mxunit-launcher.cfc";//generateUniqueName("mxunit-launcher", project); LOG.debug("Copying script file" + launcherFileName + " to component folder: " + directory); createFile(project, directory, launcherFileName, getLauncherText("/scripts/mxunit-launcher.cfc")); final String resultsFileName = "mxunit-result-capture.cfc";//generateUniqueName("mxunit-result-capture", project); LOG.debug("Copying results capture file " + resultsFileName + " to component folder: " + directory); createFile(project, directory, resultsFileName, getLauncherText("/scripts/mxunit-result-capture.cfc")); // retrieving data through URL String webPath = params.getWebPath(); if (webPath.endsWith("/") || webPath.endsWith("\\")) { webPath = webPath.substring(0, webPath.length() - 1); } String agentPath = webPath.substring(0, webPath.lastIndexOf('/')) + "/" + launcherFileName; LOG.debug("Retrieving data from coldfusion server by " + agentPath + " URL"); BufferedReader reader = null; String agentUrl; if (params.getScope() == CfmlUnitRunnerParameters.Scope.Directory) { agentUrl = agentPath + "?method=executeDirectory&directoryName=" + componentFile.getName(); } else { agentUrl = agentPath + "?method=executeTestCase&componentName=" + componentFile.getNameWithoutExtension(); if (params.getScope() == CfmlUnitRunnerParameters.Scope.Method) { agentUrl += "&methodName=" + params.getMethod(); } } HttpMethod method = null; try { LOG.debug("Retrieving test results from: " + agentUrl); /* final FileObject httpFile = getManager().resolveFile(agentUrl); reader = new BufferedReader(new InputStreamReader(httpFile.getContent().getInputStream())); */ HttpClient client = new HttpClient(); method = new GetMethod(agentUrl); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.debug("Http request failed: " + method.getStatusLine()); processHandler.notifyTextAvailable("Http request failed: " + method.getStatusLine(), ProcessOutputTypes.SYSTEM); } final InputStream responseStream = method.getResponseBodyAsStream(); reader = new BufferedReader(new InputStreamReader(responseStream)); String line; while (!processHandler.isProcessTerminating() && !processHandler.isProcessTerminated() && (line = reader.readLine()) != null) { if (!StringUtil.isEmptyOrSpaces(line)) { LOG.debug("MXUnit: " + line); processHandler.notifyTextAvailable(line + "\n", ProcessOutputTypes.SYSTEM); } } } catch (IOException e) { LOG.warn(e); processHandler.notifyTextAvailable( "Failed to retrieve test results from the server at " + agentUrl + "\n", ProcessOutputTypes.SYSTEM); } finally { if (method != null) { method.releaseConnection(); } if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } } LOG.debug("Cleaning temporary files"); deleteFile(project, directory.findChild(launcherFileName)); deleteFile(project, directory.findChild(resultsFileName)); if (!processHandler.isProcessTerminated() && !processHandler.isProcessTerminating()) { processHandler.destroyProcess(); } } catch (ExecutionException e) { ref.set(e); } }); if (!ref.isNull()) { throw ref.get(); } }
From source file:com.zimbra.qa.unittest.TestZimbraHttpConnectionManager.java
public static void dumpResponse(int respCode, HttpMethod method, String prefix) throws IOException { prefix = prefix + " - "; // status//from w w w. j ava2 s . co m int statusCode = method.getStatusCode(); String statusLine = method.getStatusLine().toString(); System.out.println(prefix + "respCode=" + respCode); System.out.println(prefix + "statusCode=" + statusCode); System.out.println(prefix + "statusLine=" + statusLine); // headers System.out.println(prefix + "Headers"); Header[] respHeaders = method.getResponseHeaders(); for (int i = 0; i < respHeaders.length; i++) { String header = respHeaders[i].toString(); // trim the CRLF at the end to save space System.out.println(prefix + header.trim()); } // body byte[] bytes = ByteUtil.getContent(method.getResponseBodyAsStream(), 0); System.out.println(prefix + bytes.length + " bytes read"); System.out.println(new String(bytes)); }