List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBody
public abstract byte[] getResponseBody() throws IOException;
From source file:org.hydracache.client.transport.HttpTransport.java
@Override public ResponseMessage sendRequest(RequestMessage requestMessage) throws Exception { if (httpClient == null) throw new IllegalStateException("Establish connection first."); HttpMethod getMethod = getMethod(requestMessage); try {/*from w ww . j av a 2s.c o m*/ int responseCode = httpClient.executeMethod(getMethod); if (responseCode == HttpStatus.SC_NOT_FOUND) return null; ResponseMessageHandler handler = handlers.get(responseCode); return (handler == null ? null : handler.accept(responseCode, getMethod.getResponseBody())); } finally { getMethod.releaseConnection(); } }
From source file:org.infoscoop.request.filter.ProxyFilterContainer.java
public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception { int preStatus = prepareInvoke(client, method, request); switch (preStatus) { case 0:/* w w w. j ava 2 s. c o m*/ break; case EXECUTE_POST_STATUS: doFilterChain(request, request.getResponseBody()); default: return preStatus; } // copy headers sent target server List ignoreHeaderNames = request.getIgnoreHeaders(); List allowedHeaderNames = request.getAllowedHeaders(); boolean allowAllHeader = false; Proxy proxy = request.getProxy(); if (proxy != null) { allowAllHeader = proxy.isAllowAllHeader(); if (!allowAllHeader) allowedHeaderNames.addAll(proxy.getAllowedHeaders()); } AuthenticatorUtil.doAuthentication(client, method, request); StringBuffer headersSb = new StringBuffer(); for (String name : request.getRequestHeaders().keySet()) { String value = request.getRequestHeader(name); String lowname = name.toLowerCase(); if (!allowAllHeader && !allowedHeaderNames.contains(lowname)) continue; if (ignoreHeaderNames.contains(lowname)) continue; if ("cookie".equalsIgnoreCase(name)) { if (proxy.getSendingCookies() != null) { value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies()); } } if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value)) continue; method.addRequestHeader(new Header(name, value)); headersSb.append(name + "=" + value + ", "); } int cacheStatus = getCache(client, method, request); if (cacheStatus != 0) return cacheStatus; if (log.isInfoEnabled()) log.info("RequestHeader: " + headersSb); // execute http method and process redirect method.setFollowRedirects(false); client.executeMethod(method); int statusCode = method.getStatusCode(); for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) { // connection release method.releaseConnection(); if (i == 5) { log.error("The circular redirect is limited by five times."); return 500; } Header location = method.getResponseHeader("Location"); String redirectUrl = location.getValue(); // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL, // but microsoft.com gives back the relative URL. if (redirectUrl.startsWith("/")) { URI baseURI = method.getURI(); baseURI.setPath(redirectUrl); redirectUrl = baseURI.toString(); } //method.setURI(new URI(redirectUrl, false)); Header[] headers = method.getRequestHeaders(); method = new GetMethod(redirectUrl); for (int j = 0; j < headers.length; j++) { String headerName = headers[j].getName(); if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization")) method.setRequestHeader(headers[j]); } AuthenticatorUtil.doAuthentication(client, method, request); method.setRequestHeader("authorization", request.getRequestHeader("Authorization")); method.setFollowRedirects(false); client.executeMethod(method); statusCode = method.getStatusCode(); request.setRedirectURL(redirectUrl); if (log.isInfoEnabled()) log.info("Redirect " + request.getTargetURL() + " to " + location + "."); } // copy response headers to proxyReqeust Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { request.putResponseHeader(headers[i].getName(), headers[i].getValue()); } if (log.isInfoEnabled()) log.info("Original Status:" + statusCode); // check response code if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { log.error("Proxy Authentication Required. Confirm ajax proxy setting."); throw new Exception( "Http Status 407, Proxy Authentication Required. Please contuct System Administrator."); } if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) { return statusCode; } else if (statusCode < 200 || statusCode >= 300) { request.setResponseBody(method.getResponseBodyAsStream()); return statusCode; } // process response body InputStream responseStream = null; if (statusCode != HttpStatus.SC_NO_CONTENT) { if (request.allowUserPublicCache()) { byte[] responseBody = method.getResponseBody(); Map<String, List<String>> responseHeaders = request.getResponseHeaders(); if (request.getRedirectURL() != null) responseHeaders.put("X-IS-REDIRECTED-FROM", Arrays.asList(new String[] { request.getRedirectURL() })); if (method instanceof GetMethod) { putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders); } responseStream = new ByteArrayInputStream(responseBody); } else { responseStream = method.getResponseBodyAsStream(); } } doFilterChain(request, responseStream); return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200; }
From source file:org.infoscoop.request.ProxyRequestTest.java
public static void main(String args[]) throws HttpException, IOException { //testActiveMailFilter(); //testCalendarFilter(); //testNekoFilter(); //testMakeMenuFilter(); //testRssFilter(); //testNoOperationFilter(); //testURLReplaceFilter(); //testMaximizeGadgetFilter(); //testSearchResultFilter(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://loclahost/ntlmtest/inicio.xml"); method.setRequestHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*"); method.setRequestHeader("Accept-Language", "ja,en;q=0.5"); method.setRequestHeader("Accept-Encoding", "gzip, deflate"); method.setRequestHeader("If-Modified-Since", "Wed, 14 May 2008 07:15:21 GMT"); method.setRequestHeader("If-None-Match", "\"3d6c2-23f3-8b33cdb5\""); method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"); method.setRequestHeader("Host", "localhost"); method.setRequestHeader("Connection", "Keep-Alive"); method.setRequestHeader("Authorization", "NTLM TlRMTVNTUAADAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAABcKIogUBKAoAAAAP"); method.setRequestHeader("Cookie", "Apache=58.80.230.67.214291213856606176"); client.executeMethod(method);//from ww w.j a va 2 s . c om method.getResponseBody(); }
From source file:org.j2free.http.HttpCallResult.java
/** * //from w w w.j a v a 2 s. co m * @param method * @throws IOException */ public HttpCallResult(HttpMethod method) throws IOException { this.method = method; this.response = method.getResponseBodyAsString(); this.bytes = method.getResponseBody(); requestHeaders = new HashMap(); responseHeaders = new HashMap(); Header[] headers = method.getRequestHeaders(); for (Header header : headers) { requestHeaders.put(header.getName(), header); } headers = method.getResponseHeaders(); for (Header header : headers) { responseHeaders.put(header.getName(), header); } status = method.getStatusLine(); }
From source file:org.jboss.test.cluster.apache_tomcat.HttpSessionReplicationTestCase.java
/** * Makes a http call to the jsp that retrieves the attribute stored on the * session. When the attribute values mathes with the one retrieved earlier, * we have HttpSessionReplication./* w ww.ja va2s. c om*/ * Makes use of commons-httpclient library of Apache * * @param client * @param method * @return session attribute */ private String makeGet(HttpClient client, HttpMethod method) { try { client.executeMethod(method); } catch (HttpRecoverableException e) { log.debug("A recoverable exception occurred, retrying." + e.getMessage()); } catch (IOException e) { log.debug(e); e.printStackTrace(); System.exit(-1); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data return new String(responseBody); }
From source file:org.jboss.test.cluster.httpsessionreplication.HttpSessionReplicationUnitTestCase.java
/** * Makes a http call to the jsp that retrieves the attribute stored on the * session. When the attribute values mathes with the one retrieved earlier, * we have HttpSessionReplication./*from ww w .j av a 2s. c o m*/ * Makes use of commons-httpclient library of Apache * @param client * @param method * @return session attribute * @throws IOException */ private String makeGet(HttpClient client, HttpMethod method) throws IOException { // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { System.err.println("A recoverable exception occurred, retrying." + e.getMessage()); } catch (IOException e) { System.err.println("Failed to download file."); e.printStackTrace(); System.exit(-1); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data return new String(responseBody); }
From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java
@Test public void shouldNotInjectLiveReloadScriptInHtmlPage() throws Exception { // pre-condition createAndLaunchLiveReloadServer(false); final String scriptContent = new StringBuilder( "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':") .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>") .toString();/*from ww w . j ava 2 s . c o m*/ // operation HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(indexDocumentlocation); int status = client.executeMethod(method); // verification assertThat(status).isEqualTo(HttpStatus.SC_OK); // Read the response body. String responseBody = new String(method.getResponseBody()); assertThat(responseBody).doesNotContain(scriptContent); }
From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java
@Test public void shouldInjectLiveReloadScriptInHtmlPageWithSimpleAcceptedTypes() throws Exception { // pre-condition createAndLaunchLiveReloadServer(true); final String scriptContent = new StringBuilder( "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':") .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>") .toString();//from w w w .jav a2 s . c om // operation HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(indexDocumentlocation); method.addRequestHeader("Accept", "text/html"); int status = client.executeMethod(method); // verification assertThat(status).isEqualTo(HttpStatus.SC_OK); // Read the response body. String responseBody = new String(method.getResponseBody()); assertThat(responseBody).contains(scriptContent); }
From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java
@Test public void shouldInjectLiveReloadScriptInHtmlPageWithSimpleAcceptedTypeAndcharset() throws Exception { // pre-condition createAndLaunchLiveReloadServer(true); final String scriptContent = new StringBuilder( "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':") .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>") .toString();/* w ww.j av a 2 s. c o m*/ // operation HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(indexDocumentlocation); method.addRequestHeader("Accept", "text/html;charset=UTF-8"); int status = client.executeMethod(method); // verification assertThat(status).isEqualTo(HttpStatus.SC_OK); // Read the response body. String responseBody = new String(method.getResponseBody()); assertThat(responseBody).contains(scriptContent); }
From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java
@Test public void shouldInjectLiveReloadScriptInHtmlPageWithMultipleAcceptedTypeAndQualityFactors() throws Exception { // pre-condition createAndLaunchLiveReloadServer(true); final String scriptContent = new StringBuilder( "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':") .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>") .toString();/*from w w w . ja v a 2 s. co m*/ // operation HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(indexDocumentlocation); method.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); int status = client.executeMethod(method); // verification assertThat(status).isEqualTo(HttpStatus.SC_OK); // Read the response body. String responseBody = new String(method.getResponseBody()); assertThat(responseBody).contains(scriptContent); }