List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString
public abstract String getResponseBodyAsString() throws IOException;
From source file:org.pentaho.versionchecker.VersionChecker.java
/** * Performs the version check by sending the request to the Pentaho server and passing the results off to the * specified results checker. If an error is encountered, the error handlers will be notified. <br> * NOTE: If no DataProvider is specified, this method will still execute. *//*from w w w .j ava 2s . c o m*/ public void performCheck(boolean ignoreExistingUpdates) { final HttpClient httpClient = getHttpClient(); final HttpMethod httpMethod = getHttpMethod(); try { int timeout = 30000; try { timeout = Integer.parseInt(DEFAULT_TIMEOUT_MILLIS); } catch (Exception e) { // ignore if (DEBUGGING) { e.printStackTrace(); } } httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout); // Set the URL and parameters setURL(httpMethod, guid); // Execute the request final int resultCode = httpClient.executeMethod(httpMethod); if (resultCode != HttpURLConnection.HTTP_OK) { // TODO - improve this throw new Exception("Invalid Result Code Returned: " + resultCode); //$NON-NLS-1$ } String resultXml = httpMethod.getResponseBodyAsString(); resultXml = checkForUpdates(dataProvider, resultXml, props, ignoreExistingUpdates); // Pass the results along processResults(resultXml); // save properties file with updated timestamp // note that any updates changed above will be saved also if (dataProvider != null) { String lastCheckProp = PROP_ROOT + "." + dataProvider.getApplicationID() + "." + //$NON-NLS-1$ //$NON-NLS-2$ dataProvider.getApplicationVersion() + "." + PROP_LASTCHECK; //$NON-NLS-1$ props.setProperty(lastCheckProp, new Date().toString()); saveProperties(); } // Clean up httpMethod.releaseConnection(); } catch (Exception e) { // IOException covers URIExcecption and HttpException if (DEBUGGING) { e.printStackTrace(); } handleException(e); } }
From source file:org.red5.server.net.rtmpt.RTMPTClientConnector.java
private void checkResponseCode(HttpMethod method) { if (method.getStatusCode() != HttpStatus.SC_OK) { try {/* w ww. jav a 2s . com*/ String body = method.getResponseBodyAsString(); throw new RuntimeException( "Bad HTTP status returned, line: " + method.getStatusLine() + "; body: " + body); } catch (IOException e) { throw new RuntimeException("Bad HTTP status returned, line: " + method.getStatusLine() + "; in addition IOException occured on reading body", e); } } }
From source file:org.red5.server.service.Installer.java
/** * Returns a Map containing all of the application wars in the snapshot repository. * //from w w w. j a va2 s . c om * @return async message */ public AsyncMessage getApplicationList() { AcknowledgeMessage result = new AcknowledgeMessage(); // create a singular HttpClient object HttpClient client = new HttpClient(); // set the proxy (WT) // test if we received variables on the commandline if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HostConfiguration config = client.getHostConfiguration(); config.setProxy(System.getProperty("http.proxyHost").toString(), Integer.parseInt(System.getProperty("http.proxyPort"))); } // establish a connection within 5 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //get the params for the client HttpClientParams params = client.getParams(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); //get registry file HttpMethod method = new GetMethod(applicationRepositoryUrl + "registry-0.9.xml"); //follow any 302's although there shouldnt be any method.setFollowRedirects(true); // execute the method try { IConnection conn = Red5.getConnectionLocal(); int code = client.executeMethod(method); log.debug("HTTP response code: {}", code); String xml = method.getResponseBodyAsString(); log.trace("Response: {}", xml); //prepare response for flex result.body = xml; result.clientId = conn.getClient().getId(); result.messageId = UUID.randomUUID().toString(); result.timestamp = System.currentTimeMillis(); //send the servers java version so the correct apps are installed String javaVersion = System.getProperty("java.version"); if (!ServiceUtils.invokeOnConnection(conn, "onJavaVersion", new Object[] { javaVersion })) { log.warn("Client call to onJavaVersion failed"); } } catch (HttpException he) { log.error("Http error connecting to {}", applicationRepositoryUrl, he); } catch (IOException ioe) { log.error("Unable to connect to {}", applicationRepositoryUrl, ioe); } finally { if (method != null) { method.releaseConnection(); } } return result; }
From source file:org.roosster.RoossterTestCase.java
/** * //from w w w . j a v a2 s. com */ public void logMethodResponse(HttpMethod method) throws java.io.IOException { if (method == null) throw new IllegalArgumentException("FAILED: Tried to log 'null' method"); if (method.isRequestSent() == false) throw new IllegalArgumentException("FAILED: Tried to log 'not-sent' method"); System.out.println("++++++++++++++++++++++++ BEGIN HEADER LOGGING ++++++++++++++++++++++++"); StatusLine sline = method.getStatusLine(); System.out.println("\nStatusLine: " + sline.getHttpVersion() + " " + sline.getStatusCode() + " " + sline.getReasonPhrase()); System.out.println("\nHeader:\n"); Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i].toString()); } System.out.println("\nResponseBody:\n" + method.getResponseBodyAsString() + "\n\n"); System.out.println("++++++++++++++++++++++++ END HEADER LOGGING ++++++++++++++++++++++++\n\n"); }
From source file:org.smartfrog.projects.alpine.transport.http.HttpTransportFault.java
private void bind(HttpMethod method) { status = method.getStatusCode();//from w ww .j av a 2 s .c o m statusLine = method.getStatusText(); try { response = method.getResponseBodyAsString(); } catch (IOException e) { log.warn("Could not read response of fault", e); } addDetail(FaultConstants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(status)); }
From source file:org.sonatype.nexus.bundle.launcher.support.RequestUtils.java
/** * Execute HttpMethod with default Nexus admin credentials * * @param method//from ww w . ja v a2s. c o m * @return * @throws HttpException * @throws IOException */ public static HttpMethod executeHTTPClientMethodAsAdmin(final HttpMethod method) throws HttpException, IOException { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin123")); List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); httpClient.getParams().setAuthenticationPreemptive(true); try { httpClient.executeMethod(method); method.getResponseBodyAsString(); // forced consumption of response I guess return method; } finally { method.releaseConnection(); // force socket cleanup HttpConnectionManager mgr = httpClient.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } }
From source file:org.sonatype.nexus.bundle.launcher.support.RequestUtils.java
public static boolean isNexusRESTStarted(final String nexusBaseURI) throws IOException, HttpException { Preconditions.checkNotNull(nexusBaseURI); final String serviceStatusURI = nexusBaseURI.endsWith("/") ? nexusBaseURI + "service/local/status" : nexusBaseURI + "/service/local/status"; org.apache.commons.httpclient.HttpMethod method = null; try {/*from w w w. j a va 2 s. co m*/ method = new GetMethod(serviceStatusURI); // only try once makes sense by default DefaultHttpMethodRetryHandler oneRetry = new DefaultHttpMethodRetryHandler(1, true); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, oneRetry); method = executeHTTPClientMethodAsAdmin(method); final int statusCode = method.getStatusCode(); if (statusCode != 200) { LOG.debug("Status check returned status " + statusCode); return false; } final String entityText = method.getResponseBodyAsString(); if (entityText == null || !entityText.contains("<state>STARTED</state>")) { LOG.debug("Status check returned invalid system state. Status: " + entityText); return false; } return true; } finally { if (method != null) { method.releaseConnection(); // request facade does this but just making sure } } }
From source file:org.sonatype.nexus.integrationtests.nexus4548.Nexus4548RepoTargetPermissionMatchesPathInRepoIT.java
@Test public void testAccessDenied() throws Exception { get("g/b/v/b-v.pom", 403); put("g/b/v/b-v-deploy.pom", 403); final HttpMethod httpMethod = putRest("b", 403); final String responseBody = httpMethod.getResponseBodyAsString(); assertThat(responseBody, containsString("<error>")); }
From source file:org.sonatype.nexus.integrationtests.NexusRestClient.java
/** * Execute a HTTPClient method, optionally in the context of a test. * <p/>// www. ja va 2s. c o m * NOTE: Before being returned, {@link org.apache.commons.httpclient.HttpMethod#releaseConnection()} is called on the {@link org.apache.commons.httpclient.HttpMethod} instance, * therefore subsequent calls to get response body as string may return nulls. * * @param method the method to execute * @param useTestContext if true, execute this request in the context of a Test, false means ignore the testContext * settings * @return the HttpMethod instance passed into this method * @throws java.io.IOException */ public HttpMethod executeHTTPClientMethod(final HttpMethod method, final boolean useTestContext) throws IOException { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000); if (useTestContext) { if (testContext.isSecureTest()) { httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(testContext.getUsername(), testContext.getPassword())); List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); httpClient.getParams().setAuthenticationPreemptive(true); } } try { httpClient.executeMethod(method); method.getResponseBodyAsString(); // forced consumption of response I guess return method; } finally { method.releaseConnection(); // force socket cleanup HttpConnectionManager mgr = httpClient.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } }
From source file:org.sonatype.nexus.test.utils.NexusStatusUtil.java
public boolean isNexusRESTStarted() throws NexusIllegalStateException { final String statusURI = AbstractNexusIntegrationTest.nexusBaseUrl + RequestFacade.SERVICE_LOCAL + "status"; // by not using test context we are only checking anonymously - this may not be a good idea, not sure org.apache.commons.httpclient.HttpMethod method = null; try {/*from w w w . j a va 2s . c om*/ try { method = RequestFacade.executeHTTPClientMethod(new GetMethod(statusURI), false); } catch (HttpException ex) { throw new NexusIllegalStateException("Problem executing status request: ", ex); } catch (IOException ex) { throw new NexusIllegalStateException("Problem executing status request: ", ex); } final int statusCode = method.getStatusCode(); // 200 if anonymous access is enabled // 401 if nexus is running but anonymous access is disabled if (statusCode == 401) { return true; } else if (statusCode != 200) { log.debug("Status check returned status " + statusCode); return false; } String entityText; try { entityText = method.getResponseBodyAsString(); } catch (IOException e) { throw new NexusIllegalStateException("Unable to retrieve nexus status body", e); } StatusResourceResponse status = (StatusResourceResponse) XStreamFactory.getXmlXStream() .fromXML(entityText); if (!SystemState.STARTED.toString().equals(status.getData().getState())) { log.debug("Status check returned system state " + status.getData().getState()); return false; } return true; } finally { if (method != null) { method.releaseConnection(); // request facade does this but just making sure } } }