List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString
public abstract String getResponseBodyAsString() throws IOException;
From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java
/** * Response//from w w w . j a va2 s . com * * @param httpMethod * @return */ String getContent(HttpMethod httpMethod) { StringBuilder contentBuilder = new StringBuilder(); if (isZipContent(httpMethod)) { // InputStream is = null; GZIPInputStream gzin = null; InputStreamReader isr = null; BufferedReader br = null; try { is = httpMethod.getResponseBodyAsStream(); gzin = new GZIPInputStream(is); isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // br = new BufferedReader(isr); char[] buffer = new char[4096]; int readlen = -1; while ((readlen = br.read(buffer, 0, 4096)) != -1) { contentBuilder.append(buffer, 0, readlen); } } catch (Exception e) { log.error("", e); } finally { try { br.close(); } catch (Exception e1) { // ignore } try { isr.close(); } catch (Exception e1) { // ignore } try { gzin.close(); } catch (Exception e1) { // ignore } try { is.close(); } catch (Exception e1) { // ignore } } } else { // String content = null; try { content = httpMethod.getResponseBodyAsString(); } catch (Exception e) { log.error("", e); } if (null == content) { return null; } contentBuilder.append(content); } return contentBuilder.toString(); }
From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java
/** * ?Response??//from w w w.j a v a 2 s . c o m * * @param httpMethod * @return */ String getContent(HttpMethod httpMethod) { StringBuilder contentBuilder = new StringBuilder(); if (isZipContent(httpMethod)) { // ??? InputStream is = null; GZIPInputStream gzin = null; InputStreamReader isr = null; BufferedReader br = null; try { is = httpMethod.getResponseBodyAsStream(); gzin = new GZIPInputStream(is); isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // ????? br = new BufferedReader(isr); char[] buffer = new char[4096]; int readlen = -1; while ((readlen = br.read(buffer, 0, 4096)) != -1) { contentBuilder.append(buffer, 0, readlen); } } catch (Exception e) { log.error("", e); } finally { try { br.close(); } catch (Exception e1) { // ignore } try { isr.close(); } catch (Exception e1) { // ignore } try { gzin.close(); } catch (Exception e1) { // ignore } try { is.close(); } catch (Exception e1) { // ignore } } } else { // ??? String content = null; try { content = httpMethod.getResponseBodyAsString(); } catch (Exception e) { log.error("???", e); } if (null == content) { return null; } contentBuilder.append(content); } return contentBuilder.toString(); }
From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java
public SaxonDocument getStats(String collectionId) throws UnsupportedEncodingException, IOException, SaxonApiException, Exception { HttpClient client = new HttpClient(); HttpMethod method; String fq = !collectionId.isEmpty() ? "fq=parentIdentifier%3D" + collectionId + "&" : ""; String urlStr = this.solrHost + "/select?q=*%3A*&" + fq + "wt=xml&stats=true&" + "stats.field=beginPosition&" + "stats.field=endPosition&" + "stats.field=orbitNumber&" + "stats.field=acquisitionStation&" + "facet.field=productType&" + "facet.field=platformShortName&" + "facet.field=platformSerialIdentifier&" + "facet.field=instrument&" + "facet.field=sensorType&" + "facet.field=compositeType&" + "facet.field=processingLevel&" + "facet.field=orbitType&" + "stats.field=resolution&" + "facet.field=spectralRange&" + "stats.field=wavelengths&" + "facet.field=useLimitation&" + "facet.field=hasSecurityConstraints&" + "facet.field=organisationName&" + "facet.field=dissemination&" + "facet.field=parentIdentifier&" + "facet.field=productionStatus&" + "facet.field=acquisitionType&" + "stats.field=orbitNumber&" + "facet.field=orbitDirection&" + "stats.field=track&" + "stats.field=frame&" + "facet.field=swathIdentifier&" + "stats.field=cloudCover&" + "stats.field=snowCover&" + "facet.field=productQualityDegradation&" + "facet.field=productQualityDegradationTag&" + "facet.field=processorName&" + "facet.field=processingCenter&" + "stats.field=processingDate&" + "facet.field=sensorMode&" + "facet.field=archivingCenter&" + "facet.field=processingMode&" + "facet.field=acquisitionStation&" + "facet.field=acquisitionSubType&" + "stats.field=startTimeFromAscendingNode&" + "stats.field=completionTimeFromAscendingNode&" + "stats.field=illuminationAzimuthAngle&" + "stats.field=illuminationZenithAngle&" + "stats.field=illuminationElevationAngle&" + "facet.field=polarisationMode&" + "facet.field=polarisationChannels&" + "facet.field=antennaLookDirection&" + "stats.field=minimumIncidenceAngle&" + "stats.field=maximumIncidenceAngle&" + "stats.field=dopplerFrequency&" + "stats.field=incidenceAngleVariation&" + "rows=0&indent=true&facet=on&facet.mincount=1"; Log.debug("The following search is goint to be executed:" + urlStr); // Create a method instance. method = new GetMethod(urlStr); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = client.executeMethod(method); SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString()); Log.debug(solrResponse.getXMLDocumentString()); if (statusCode != HttpStatus.SC_OK) { Log.error("Method failed: " + method.getStatusLine()); String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()", XPathConstants.STRING); Log.error(solrResponse.getXMLDocumentString()); throw new Exception(errorMessage); }/*from www .j a v a 2 s . c o m*/ return solrResponse; }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Writes tracing information that traces the request/response activity. * /*from w ww . jav a 2s. c om*/ * @param traceLevel * Indicates how much trace info to produce. * @param traceStream * An output stream where trace statements will be written. * @param httpMethod * The HttpMethod object of the request. */ private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) { try { if (traceLevel >= TRACE_URI) { // Show trace output of the request URI traceStream .println("-------------------------------------------------------------------------------"); traceStream.println(httpMethod.getURI() + "\n"); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP request line traceStream.println(httpMethod.getName() + " " + httpMethod.getPath() + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " " + httpMethod.getParams().getVersion().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP request headers for (Header header : httpMethod.getRequestHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } // Show trace of request entity body if (httpMethod instanceof PostMethod) { NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters(); if (parameters != null) { // StringBuffer parameterString = new StringBuffer(); // for (NameValuePair parameter : parameters) { // parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&"); // } // parameterString.deleteCharAt(parameterString.length() - 1); String parameterString = new String( ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity()) .getContent(), "UTF-8"); traceStream.println(" |"); traceStream.println(" +-- " + parameterString); } } traceStream.println(); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP status line traceStream.println(httpMethod.getStatusLine().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP response headers for (Header header : httpMethod.getResponseHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } traceStream.println(); } if (traceLevel >= TRACE_BODY) { // Show trace output of the HTTP response body traceStream.println(httpMethod.getResponseBodyAsString()); traceStream.println(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:io.hops.hopsworks.api.jobs.JobService.java
/** * Get the job ui for the specified job. * This act as a proxy to get the job ui from yarn * <p>// w w w. j ava 2 s .c o m * @param appId * @param param * @param sc * @param req * @return */ @GET @Path("/{appId}/prox/{path: .+}") @Produces(MediaType.WILDCARD) @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param, @Context SecurityContext sc, @Context HttpServletRequest req) { Response response = checkAccessRight(appId); if (response != null) { return response; } try { String trackingUrl; if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) { trackingUrl = param; } else { trackingUrl = "http://" + param; } trackingUrl = trackingUrl.replace("@hwqm", "?"); if (!hasAppAccessRight(trackingUrl)) { LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!"); return Response.status(Response.Status.FORBIDDEN).build(); } org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false); HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); final HttpMethod method = new GetMethod(uri.getEscapedURI()); Enumeration<String> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String value = req.getHeader(name); if (PASS_THROUGH_HEADERS.contains(name)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) { method.setRequestHeader(name, value); } } } String user = req.getRemoteUser(); if (user != null && !user.isEmpty()) { method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(method); Response.ResponseBuilder responseBuilder = noCacheResponse .getNoCacheResponseBuilder(Response.Status.OK); for (Header header : method.getResponseHeaders()) { responseBuilder.header(header.getName(), header.getValue()); } //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab //which are in a json response object if (method.getResponseHeader("Content-Type") == null || method.getResponseHeader("Content-Type").getValue().contains("html") || method.getPath().contains("/allexecutors")) { final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort(); if (method.getResponseHeader("Content-Length") == null) { responseBuilder.entity(new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(out)); InputStream stream = method.getResponseBodyAsStream(); Reader in = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[4 * 1024]; String remaining = ""; int n; while ((n = in.read(buffer)) != -1) { StringBuilder strb = new StringBuilder(); strb.append(buffer, 0, n); String s = remaining + strb.toString(); remaining = s.substring(s.lastIndexOf(">") + 1, s.length()); s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source); writer.write(s); } writer.flush(); } }); } else { String s = hopify(method.getResponseBodyAsString(), param, appId, source); responseBuilder.entity(s); responseBuilder.header("Content-Length", s.length()); } } else { responseBuilder.entity(new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { InputStream stream = method.getResponseBodyAsStream(); org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true); out.flush(); } }); } return responseBuilder.build(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e); return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build(); } }
From source file:net.ushkinaz.storm8.http.HttpHelper.java
public static String getHttpResponse(HttpClient httpClient, HttpMethod httpMethod) { String asString = ""; try {//from w w w.j av a 2s . co m int statusCode = httpClient.executeMethod(httpMethod); if (statusCode != 200) { throw new IOException("Can't access page : " + httpMethod.getURI()); } asString = httpMethod.getResponseBodyAsString(); } catch (IOException e) { LOGGER.error("Error", e); } return asString; }
From source file:nl.b3p.viewer.image.ImageTool.java
/** Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage/*from w ww . java2 s.c om*/ * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(HttpMethod method, String mime) throws Exception { ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); throw new Exception("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! InputStream is = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
From source file:org.agnitas.dao.impl.VersionControlDaoImpl.java
private String fetchServerVersion(String currentVersion, String referrer) { HttpClient client = new HttpClient(); client.setConnectionTimeout(CONNECTION_TIMEOUT); HttpMethod method = new GetMethod(URL); method.setRequestHeader("referer", referrer); NameValuePair[] queryParams = new NameValuePair[1]; queryParams[0] = new NameValuePair(VERSION_KEY, currentVersion); method.setQueryString(queryParams);/*from w ww . java 2 s.c o m*/ method.setFollowRedirects(true); String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (Exception he) { logger.error("HTTP error connecting to '" + URL + "'", he); } //clean up the connection resources method.releaseConnection(); return responseBody; }
From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java
/** * Debugging method for obtaining the state of a response as a String. * /* w w w.j a v a 2 s .com*/ * @param method The method to retrieve the response state from <i>(may be null)</i>. * @return The response state as a human-readable string value <i>(will not be null)</i>. */ private String responseToString(final HttpMethod method) { StringBuffer result = new StringBuffer(128); if (method != null) { result.append("\n\tStatus: "); result.append(method.getStatusCode()); result.append(" "); result.append(method.getStatusText()); result.append("\n\tHeaders: "); for (final Header header : method.getResponseHeaders()) { result.append("\n\t\t"); result.append(header.getName()); result.append(" : "); result.append(header.getValue()); } result.append("\n\tBody:"); result.append("\n"); try { result.append(method.getResponseBodyAsString()); } catch (final IOException ioe) { result.append("unknown, due to: " + ioe.getMessage()); } } else { result.append("(null)"); } return (result.toString()); }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
/** * * @param methodName String/*from w w w . ja v a 2s. co m*/ * @param response int * @param method HttpMethod */ private void checkResponseStatus(String methodName, int response, HttpMethod method) { if (response != 200) { Throwable error = null; try { log.error("Received \"unsuccessful\" response code from target server: " + response); String errorPayload = method.getResponseBodyAsString(); JSONObject errorObj = new JSONObject(errorPayload); error = rehydrateError(errorObj); } catch (Exception ex) { throw new TransferException(MSG_UNSUCCESSFUL_RESPONSE, new Object[] { methodName, response }); } if ((error != null) && TransferException.class.isAssignableFrom(error.getClass())) { throw (TransferException) error; } else { throw new TransferException(MSG_UNSUCCESSFUL_RESPONSE, new Object[] { methodName, response }); } } }