List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBody
public abstract byte[] getResponseBody() throws IOException;
From source file:org.apache.roller.weblogger.util.Trackback.java
/** * Sends trackback from entry to remote URL. * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec *///from w w w .j a v a2s . c o m public RollerMessages send() throws WebloggerException { RollerMessages messages = new RollerMessages(); log.debug("Sending trackback to url - " + trackbackURL); // Construct data String title = entry.getTitle(); String excerpt = StringUtils.left(Utilities.removeHTML(entry.getDisplayContent()), 255); String url = entry.getPermalink(); String blog_name = entry.getWebsite().getName(); // build trackback post parameters as query string Map params = new HashMap(); params.put("title", URLUtilities.encode(title)); params.put("excerpt", URLUtilities.encode(excerpt)); params.put("url", URLUtilities.encode(url)); params.put("blog_name", URLUtilities.encode(blog_name)); String queryString = URLUtilities.getQueryString(params); log.debug("query string - " + queryString); // prepare http request HttpClient client = new HttpClient(); client.setConnectionTimeout(45 * 1000); HttpMethod method = new PostMethod(trackbackURL); method.setQueryString(queryString); try { // execute trackback int statusCode = client.executeMethod(method); // read response byte[] response = method.getResponseBody(); String responseString = Utilities.escapeHTML(new String(response, "UTF-8")); log.debug("result = " + statusCode + " " + method.getStatusText()); log.debug("response:\n" + responseString); if (statusCode == HttpStatus.SC_OK) { // trackback request succeeded, message will give details try { messages = parseTrackbackResponse(new String(response, "UTF-8"), messages); } catch (Exception e) { // Cannot parse response, indicates failure messages.addError("weblogEdit.trackbackErrorParsing", responseString); } } else if (statusCode == HttpStatus.SC_NOT_FOUND) { // 404, invalid trackback url messages.addError("weblogEdit.trackbackError404"); } else { // some other kind of error with url, like 500, 403, etc // just provide a generic error message and give the http response text messages.addError("weblogEdit.trackbackErrorResponse", new String[] { "" + statusCode, method.getStatusText() }); } } catch (IOException e) { // some kind of transport error sending trackback post log.debug("Error sending trackback", e); messages.addError("weblogEdit.trackbackErrorTransport"); } finally { // release used connection method.releaseConnection(); } return messages; }
From source file:org.archive.wayback.liveweb.ArcRemoteLiveWebCache.java
public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder) throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException, IOException {/*from www .jav a2 s . c o m*/ String urlString = url.toExternalForm(); if (requestPrefix != null) { urlString = requestPrefix + urlString; } HttpMethod method = null; try { method = new GetMethod(urlString); } catch (IllegalArgumentException e) { LOGGER.warning("Bad URL for live web fetch:" + urlString); throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?"); } boolean success = false; try { int status = http.executeMethod(method); if (status == 200) { ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody()); ARCRecord r = new ARCRecord(new GZIPInputStream(bais), "id", 0L, false, false, true); ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null); if (ar.getStatusCode() == 502) { throw new LiveDocumentNotAvailableException(urlString); } else if (ar.getStatusCode() == 504) { throw new LiveWebTimeoutException("Timeout:" + urlString); } success = true; return ar; } else { throw new LiveWebCacheUnavailableException(urlString); } } catch (ResourceNotAvailableException e) { throw new LiveDocumentNotAvailableException(urlString); } catch (NoHttpResponseException e) { throw new LiveWebCacheUnavailableException("No Http Response for " + urlString); } catch (ConnectException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } catch (ConnectTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } finally { if (!success) { method.abort(); } method.releaseConnection(); } }
From source file:org.cancergrid.ws.util.HttpContentReader.java
public static String getHttpContent(String httpUrl, String query, Method method) { LOG.debug("getHttpContent(httpUrl): " + httpUrl); LOG.debug("getHttpContent(query): " + query); LOG.debug("getHttpContent(method): " + method); HttpMethod httpMethod = null; if (httpUrl.contains("&")) { httpUrl = httpUrl.replace("&", "&"); }/*from ww w . j a v a 2 s .com*/ if (query != null && query.length() > 0 && query.startsWith("?") && query.contains("&")) { query = query.replace("&", "&"); } try { //LOG.debug("Querying: " + httpUrl); if (method == Method.GET) { httpMethod = new GetMethod(httpUrl); if (query != null && query.length() > 0) { httpMethod.setQueryString(query); } } else if (method == Method.POST) { httpMethod = new PostMethod(httpUrl); if (query != null && query.length() > 0) { RequestEntity entity = new StringRequestEntity(query, "text/xml", "UTF-8"); ((PostMethod) httpMethod).setRequestEntity(entity); } } httpMethod.setFollowRedirects(true); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Protocol.registerProtocol("https", new Protocol("https", new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 443)); HttpClient client = new HttpClient(); int statusCode = client.executeMethod(httpMethod); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + httpMethod.getStatusLine()); LOG.error("Error querying: " + httpMethod.getURI().toString()); throw new Exception("Method failed: " + httpMethod.getStatusLine()); } byte[] responseBody = httpMethod.getResponseBody(); return new String(responseBody, "UTF-8"); } catch (HttpException e) { LOG.error("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { LOG.error("Fatal transport error: " + e.getMessage()); } catch (Exception e) { LOG.error(e.getMessage()); } finally { httpMethod.releaseConnection(); } return null; }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given * {@link HttpServletResponse}.//from w w w . ja v a2 s.c o m * * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient; httpClient = createClientWithLogin(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // String response = httpMethodProxyRequest.getResponseBodyAsString(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */ ) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + HEADER_LOCATION + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { httpServletResponse .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(HEADER_CONTENT_LENGTH, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) { // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); // FIXME We should handle both String and bytes response in the same way: String response = null; byte[] bodyBytes = null; if (isBodyParameterGzipped(responseHeaders)) { LOGGER.trace("GZipped: true"); if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(HEADER_LOCATION, response); httpServletResponse.setContentLength(response.length()); } else { bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody()); httpServletResponse.setContentLength(bodyBytes.length); } } if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) { LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response); } else { LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode); } // Send the content to the client if (response != null) { httpServletResponse.getWriter().write(response); } else if (bodyBytes != null) { httpServletResponse.getOutputStream().write(bodyBytes); } else { IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream()); } }
From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java
@Test public void testGetWithUnsatisfiableRange() throws IOException { final HttpClient client = new HttpClient(); // write test content: final byte[] testContent = "hello world".getBytes(); try (WritableFile w = fs.file("foo.txt").openWritable()) { w.write(ByteBuffer.wrap(testContent)); }// w ww . j a v a 2 s . c om // check get response body: final HttpMethod getMethod = new GetMethod(servletRoot + "/foo.txt"); getMethod.addRequestHeader("Range", "chunks=1-2"); final int statusCode = client.executeMethod(getMethod); Assert.assertEquals(200, statusCode); Assert.assertArrayEquals(testContent, getMethod.getResponseBody()); getMethod.releaseConnection(); }
From source file:org.dspace.app.util.AbstractDSpaceWebapp.java
/** Return the list of running applications. */ static public List<AbstractDSpaceWebapp> getApps() { ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>(); TableRowIterator tri;//from w w w . jav a2s . c o m Context context = null; HttpMethod request = null; try { context = new Context(); tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp"); for (TableRow row : tri.toList()) { DSpaceWebapp app = new DSpaceWebapp(); app.kind = row.getStringColumn("AppName"); app.url = row.getStringColumn("URL"); app.started = row.getDateColumn("Started"); app.uiQ = row.getBooleanColumn("isUI"); HttpClient client = new HttpClient(); request = new HeadMethod(app.url); int status = client.executeMethod(request); request.getResponseBody(); if (status != HttpStatus.SC_OK) { DatabaseManager.delete(context, row); context.commit(); continue; } apps.add(app); } } catch (SQLException e) { log.error("Unable to list running applications", e); } catch (HttpException e) { log.error("Failure checking for a running webapp", e); } catch (IOException e) { log.error("Failure checking for a running webapp", e); } finally { if (null != request) { request.releaseConnection(); } if (null != context) { context.abort(); } } return apps; }
From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java
protected String getResponseAsString(HttpMethod httpMethod) throws IOException { // Get response bytes byte[] responseBytes = httpMethod.getResponseBody(); String responseCharSet = null; if (httpMethod instanceof HttpMethodBase) { HttpMethodBase methodBase = (HttpMethodBase) httpMethod; responseCharSet = methodBase.getRequestCharSet(); }/*from ww w . j a v a2s. c o m*/ return getResponseAsString(responseBytes, responseCharSet); }
From source file:org.eclipse.om2m.comm.http.RestHttpClient.java
/** * Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request. * Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back. * @param requestIndication - protocol independent request. * @return protocol independent response. */// w w w. j a v a 2s .com public ResponseConfirm sendRequest(RequestIndication requestIndication) { logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(), org.osgi.service.log.LogService.class.getName(), null); logServiceTracker.open(); logservice = (LogService) logServiceTracker.getService(); LOGGER.debug("Http Client > " + requestIndication); logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication); HttpClient httpclient = new HttpClient(); ResponseConfirm responseConfirm = new ResponseConfirm(); HttpMethod httpMethod = null; String url = requestIndication.getUrl(); if (!url.startsWith(protocol + "://")) { url = protocol + "://" + url; } try { switch (requestIndication.getMethod()) { case "RETRIEVE": httpMethod = new GetMethod(url); break; case "CREATE": httpMethod = new PostMethod(url); ((PostMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "UPDATE": httpMethod = new PutMethod(url); ((PutMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "DELETE": httpMethod = new DeleteMethod(url); break; case "EXECUTE": httpMethod = new PostMethod(url); break; default: return new ResponseConfirm(); } httpMethod.addRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes()))); httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters())); int statusCode = httpclient.executeMethod(httpMethod); responseConfirm.setStatusCode(getRestStatusCode(statusCode)); if (statusCode != 204) { if (httpMethod.getResponseBody() != null) { responseConfirm.setRepresentation(new String(httpMethod.getResponseBody())); } } if (statusCode == 201) { if (httpMethod.getResponseHeader("Location").getValue() != null) { responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue()); } } //LOGGER.debug("Http Client > "+responseConfirm); LOGGER.debug("Http Client > " + responseConfirm); logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm); } catch (IOException e) { LOGGER.error(url + " Not Found" + responseConfirm, e); logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm); } finally { httpMethod.releaseConnection(); } return responseConfirm; }
From source file:org.genemania.util.HttpRetriever.java
private String fetchPage(String url) { String ret = ""; try {//from w w w .j a v a 2 s . c o m HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("HttpRetriever error: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); method.releaseConnection(); ret = new String(responseBody); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:org.gss_project.gss.web.client.TestClient.java
public static void main(String[] args) { String user = "ebstest@grnet-hq.admin.grnet.gr"; String token = "PcxaZ/4oIqCqIvCYgsUcKr1hAFcsW40G3kcWJSRPJV5GjzoNuo8RsA=="; String host = "pithos.grnet.gr"; String restPath = "/pithos/rest"; String path = "/" + user + "/files/"; String now = DateUtil.formatDate(new Date()); String signature = sign("GET", now, path, token); HttpClient client = new HttpClient(); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost(host);//from w w w . j av a2 s . co m HttpMethod method = new GetMethod(restPath + path); Collection<Header> headers = new ArrayList<Header>(); Header auth = new Header("Authorization", user + " " + signature); headers.add(auth); Header date = new Header("X-GSS-Date", now); headers.add(date); System.out.println(headers.toString()); hostconfig.getParams().setParameter("http.default-headers", headers); try { // Execute the method. int statusCode = client.executeMethod(hostconfig, method); if (statusCode != HttpStatus.SC_OK) System.err.println("Method failed: " + method.getStatusLine()); // Read the response body. byte[] responseBody = method.getResponseBody(); // 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(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }