List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java
public RedirectionPath followRedirection(HttpMethod method) throws IOException { int redirectionsCount = 0; int status = method.getStatusCode(); RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT); while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location == null) { location = method.getResponseHeader("location"); }/*from w ww . j a v a 2s .c om*/ if (location != null) { Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue()); String locationStr = location.getValue(); result.addLocation(locationStr); // Release the connection to avoid reach the max number of connections per host // due to it will be set a different url exhaustResponse(method.getResponseBodyAsStream()); method.releaseConnection(); method.setURI(new URI(locationStr, true)); Header destination = method.getRequestHeader("Destination"); if (destination == null) { destination = method.getRequestHeader("destination"); } if (destination != null) { int suffixIndex = locationStr.lastIndexOf( (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH : AccountUtils.WEBDAV_PATH_4_0); String redirectionBase = locationStr.substring(0, suffixIndex); String destinationStr = destination.getValue(); String destinationPath = destinationStr.substring(mBaseUri.toString().length()); String redirectedDestination = redirectionBase + destinationPath; destination.setValue(redirectedDestination); method.setRequestHeader(destination); } status = super.executeMethod(method); result.addStatus(status); redirectionsCount++; } else { Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); status = HttpStatus.SC_NOT_FOUND; } } return result; }
From source file:com.intuit.tank.http.BaseRequest.java
public void sendRequest(BaseResponse response, @Nonnull HttpMethod method, String requestBody) { String uri = null;/* w w w . j a v a 2s . co m*/ long waitTime = 0L; try { this.response = response; uri = method.getURI().toString(); logger.debug( LogUtil.getLogMessage("About to POST request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); logRequest(uri, requestBody, method.getName(), headerInformation, httpclient, false); BaseRequestHandler.setHeaders(method, headerInformation); long startTime = System.currentTimeMillis(); timestamp = new Date(startTime); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); BaseRequestHandler.processResponse(responseBody, startTime, endTime, response, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(LogUtil.getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { method.releaseConnection(); } if (waitTime != 0) { doWaitDueToLongResponse(waitTime, uri); } }
From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java
/** * Response/* ww w . java 2s .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:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java
/** * ?Response??//from w w w. ja 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:com.cloud.test.stress.TestClientWithAPI.java
private static boolean getNetworkStat(String server) { try {// ww w . ja va 2s . c om String url = server + "?command=listAccountStatistics&account=" + _account.get(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); s_logger.info("listAccountStatistics response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] { "receivedbytes", "sentbytes" }); int bytesReceived = Integer.parseInt(requestKeyValues.get("receivedbytes")); int bytesSent = Integer.parseInt(requestKeyValues.get("sentbytes")); if ((bytesReceived > 100000000) && (bytesSent > 0)) { s_logger.info("Network stat is correct for account" + _account.get() + "; bytest received is " + bytesReceived + " and bytes sent is " + bytesSent); return true; } else { s_logger.error("Incorrect value for bytes received/sent for the account " + _account.get() + ". We got " + bytesReceived + " bytes received; " + " and " + bytesSent + " bytes sent"); return false; } } else { s_logger.error("listAccountStatistics failed with error code: " + responseCode + ". Following URL was sent: " + url); return false; } } catch (Exception ex) { s_logger.error("Exception while sending command listAccountStatistics"); return false; } }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
/** * Reads the http response from a connection, counts the size of the * resulting document, and discards the data. This method recycles its * buffer during large reads and therefore has very little weight. * @param method The HttpMethod to read from * @return The number of bytes read// w w w. ja va 2 s . c o m * @throws java.io.IOException */ private int readResponse(HttpMethod method) throws IOException { int totalLength = 0; InputStream in; in = method.getResponseBodyAsStream(); if (in != null) { int length = in.read(byteReadBuffer); while (length != -1) { totalLength += length; length = in.read(byteReadBuffer); } in.close(); contentSize = totalLength; } return totalLength; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
public static Element queryAsyncJobResult(String host, InputStream inputStream) { Element returnBody = null;/*from w w w . ja va2 s .co m*/ Map<String, String> values = getSingleValueFromXML(inputStream, new String[] { "jobid" }); String jobId = values.get("jobid"); if (jobId == null) { s_logger.error("Unable to get a jobId"); return null; } // s_logger.info("Job id is " + jobId); String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(resultUrl); while (true) { try { client.executeMethod(method); // s_logger.info("Method is executed successfully. Following url was sent " + resultUrl); InputStream is = method.getResponseBodyAsStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); returnBody = doc.getDocumentElement(); doc.getDocumentElement().normalize(); Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); String jobStatus = jobStatusTag.getTextContent(); if (jobStatus.equals("0")) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } else { break; } } catch (Exception ex) { s_logger.error(ex); } } return returnBody; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
private static int executeEventsAndBilling(String server, String developerServer) throws HttpException, IOException { // test steps: // - get all the events in the system for all users in the system // - generate all the usage records in the system // - get all the usage records in the system // ----------------------------- // GET EVENTS // ----------------------------- String url = server + "?command=listEvents&page=1&pagesize=100&&account=" + _account.get(); s_logger.info("Getting events for the account " + _account.get()); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); s_logger.info("get events response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> eventDescriptions = getMultipleValuesFromXML(is, new String[] { "description" }); List<String> descriptionText = eventDescriptions.get("description"); if (descriptionText == null) { s_logger.info("no events retrieved..."); } else {/*from w w w . j ava 2 s . c om*/ for (String text : descriptionText) { s_logger.info("event: " + text); } } } else { s_logger.error( "list events failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ------------------------------------------------------------------------------------- // GENERATE USAGE RECORDS (note: typically this is done infrequently) // ------------------------------------------------------------------------------------- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date currentDate = new Date(); String endDate = dateFormat.format(currentDate); s_logger.info("Generating usage records from September 1st till " + endDate); url = server + "?command=generateUsageRecords&startdate=2009-09-01&enddate=" + endDate; // generate // all usage record till today client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("generate usage records response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> successStr = getSingleValueFromXML(is, new String[] { "success" }); s_logger.info("successfully generated usage records? " + successStr.get("success")); } else { s_logger.error("generate usage records failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Sleeping for a 2 minutes before getting a usage records from the database try { Thread.sleep(120000); } catch (Exception ex) { s_logger.error(ex); } // -------------------------------- // GET USAGE RECORDS // -------------------------------- url = server + "?command=listUsageRecords&startdate=2009-09-01&enddate=" + endDate + "&account=" + _account.get() + "&domaindid=1"; s_logger.info("Getting all usage records with request: " + url); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("get usage records response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> usageRecValues = getMultipleValuesFromXML(is, new String[] { "description", "usage" }); if ((usageRecValues.containsKey("description") == true) && (usageRecValues.containsKey("usage") == true)) { List<String> descriptions = usageRecValues.get("description"); List<String> usages = usageRecValues.get("usage"); for (int i = 0; i < descriptions.size(); i++) { String desc = descriptions.get(i); String usage = ""; if (usages != null) { if (i < usages.size()) { usage = ", usage: " + usages.get(i); } } s_logger.info("desc: " + desc + usage); } } } else { s_logger.error("list usage records failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } return responseCode; }
From source file:it.infn.ct.aleph_portlet.java
public void getRecordsOAR(String search, int jrec, int num_rec) { String responseXML = null;//from w ww .j a va 2s. co m HttpClient client = new HttpClient(); HttpMethod method = callAPIOAR(search, jrec, num_rec); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { method.getResponseBody(); responseXML = convertStreamToString(method.getResponseBodyAsStream()); FileWriter fw = new FileWriter( appServerPath + "datatable/marcXML_OAR_" + jrec + "_" + num_rec + ".xml"); System.out.println(); fw.append(responseXML); fw.close(); } } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
From source file:com.adobe.share.api.ShareAPI.java
/** * Parses the file response.// ww w . j av a 2 s. c o m * * @param method the method * * @return the input stream * * @throws HttpException the http exception * @throws IOException Signals that an I/O exception has occurred. * @throws ShareAPIException the share api exception */ protected final InputStream parseFileResponse(final HttpMethod method) throws HttpException, IOException, ShareAPIException { JSONObject json = null; String content = null; try { int status = httpClient.executeMethod(method); if (status >= STATUS_BAD_REQUEST) { if (json != null) { throw new ShareAPIException(method.getStatusCode(), json.getJSONObject("response").getString("message")); } else { throw new ShareAPIException(method.getStatusCode(), content); } } return method.getResponseBodyAsStream(); } catch (JSONException e) { throw new ShareAPIException(method.getStatusCode(), content); } }