List of usage examples for org.apache.http.util EntityUtils consume
public static void consume(HttpEntity httpEntity) throws IOException
From source file:org.sonar.plugins.web.markup.validation.MarkupValidator.java
/** * Post contents of HTML file to the W3C validation service. In return, receive a Soap response message. * * @see http://validator.w3.org/docs/api.html *//*from w w w . j av a2s . com*/ private void postHtmlContents(InputFile inputfile) { HttpPost post = new HttpPost(validationUrl); HttpResponse response = null; post.addHeader("User-Agent", "sonar-w3c-markup-validation-plugin/1.0"); try { LOG.info("W3C Validate: " + inputfile.getRelativePath()); // file upload MultipartEntity multiPartRequestEntity = new MultipartEntity(); String charset = CharsetDetector.detect(inputfile.getFile()); FileBody fileBody = new FileBody(inputfile.getFile(), TEXT_HTML_CONTENT_TYPE, charset); multiPartRequestEntity.addPart(UPLOADED_FILE, fileBody); // set output format multiPartRequestEntity.addPart(OUTPUT, new StringBody(SOAP12)); post.setEntity(multiPartRequestEntity); response = executePostMethod(post); // write response to report file if (response != null) { writeResponse(response, inputfile); } } catch (UnsupportedEncodingException e) { LOG.error(e); } finally { // release any connection resources used by the method if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException ioe) { LOG.debug(ioe); } } } }
From source file:com.yahoo.sql4d.sql4ddriver.DruidNodeAccessor.java
/** * This ensures the response body is completely consumed and hence the HttpClient * object will be return back to the pool successfully. * @param resp /*from w ww .j a va2s . c o m*/ */ public void returnClient(CloseableHttpResponse resp) { try { if (resp != null) { EntityUtils.consume(resp.getEntity()); } } catch (IOException ex) { //TODO: Could not consume response completely. This is serious because the client will not be returned back to pool. log.error("Error returning client to pool {}", ExceptionUtils.getStackTrace(ex)); } }
From source file:com.magnet.tools.tests.RestStepDefs.java
@When("^I send the following Rest queries:$") public static void sendRestQueries(List<RestQueryEntry> entries) throws Throwable { for (RestQueryEntry e : entries) { String url = expandVariables(e.url); StatusLine statusLine;//from w w w . j a v a 2 s . co m HttpUriRequest httpRequest; HttpEntity entityResponse; CloseableHttpClient httpClient = getTestHttpClient(new URI(url)); Object body = isStringNotEmpty(e.body) ? e.body : getRef(e.bodyRef); String verb = e.verb; if ("GET".equalsIgnoreCase(verb)) { httpRequest = new HttpGet(url); } else if ("POST".equalsIgnoreCase(verb)) { httpRequest = new HttpPost(url); ((HttpPost) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("PUT".equalsIgnoreCase(verb)) { httpRequest = new HttpPut(url); ((HttpPut) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("DELETE".equalsIgnoreCase(verb)) { httpRequest = new HttpDelete(url); } else { throw new IllegalArgumentException("Unknown verb: " + e.verb); } String response; setHttpHeaders(httpRequest, e); ScenarioUtils.log("Sending HTTP Request: " + e.url); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); statusLine = httpResponse.getStatusLine(); entityResponse = httpResponse.getEntity(); InputStream is = entityResponse.getContent(); response = IOUtils.toString(is); EntityUtils.consume(entityResponse); } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (Exception ex) { /* do nothing */ } } } ScenarioUtils.log("====> Received response body:\n " + response); Assert.assertNotNull(response); setHttpResponseBody(response); if (isStringNotEmpty(e.expectedResponseBody)) { // inline the assertion check on http response body ensureHttpResponseBody(e.expectedResponseBody); } if (isStringNotEmpty(e.expectedResponseBodyRef)) { // inline the assertion check on http response body ensureHttpResponseBody((String) getRef(e.expectedResponseBodyRef)); } if (isStringNotEmpty(e.expectedResponseContains)) { // inline the assertion check on http response body ensureHttpResponseBodyContains(e.expectedResponseContains); } if (null == statusLine) { throw new IllegalArgumentException("Status line in http response is null, request was " + e.url); } int statusCode = statusLine.getStatusCode(); ScenarioUtils.log("====> Received response code: " + statusCode); setHttpResponseStatus(statusCode); if (isStringNotEmpty(e.expectedResponseStatus)) { // inline the assertion check on http status ensureHttpResponseStatus(Integer.parseInt(e.expectedResponseStatus)); } } }
From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java
public static OOListResponse listFlows(OOServer s, String... folders) throws IOException { String foldersPath = ""; for (String folder : folders) { foldersPath += folder + "/"; }// ww w.ja v a2 s .c o m String url = StringUtils.slashify(s.getUrl()) + REST_SERVICES_URL_PATH + LIST_OPERATION_URL_PATH + foldersPath; final HttpResponse response = OOBuildStep.getHttpClient().execute(new HttpGet(OOBuildStep.URI(url))); final int statusCode = response.getStatusLine().getStatusCode(); final HttpEntity entity = response.getEntity(); try { if (statusCode == HttpStatus.SC_OK) { return JAXB.unmarshal(entity.getContent(), OOListResponse.class); } else { throw new RuntimeException("unable to get list of flows from " + url + ", response code: " + statusCode + "(" + HttpStatus.getStatusText(statusCode) + ")"); } } finally { EntityUtils.consume(entity); } }
From source file:com.sangupta.dribbble.api.DribbbleInvoker.java
/** * Hit the URL endpoint and return the response body if the status code is HTTP 200. * /*w ww . j a v a2 s . c om*/ * @param url * @return */ private static String hit(final String url) { HttpGet httpGet = new HttpGet(url); try { HttpResponse httpResponse = httpClient.execute(httpGet); final HttpEntity entity = httpResponse.getEntity(); // check for success code of HTTP 200 int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode != 200) { // consume the entity to release connection EntityUtils.consume(entity); // return null response return null; } // consume the entity String response = EntityUtils.toString(entity); return response; } catch (ClientProtocolException e) { logger.log(Level.WARNING, "Unable to hit dribbble endpoint: " + url, e); } catch (IOException e) { logger.log(Level.WARNING, "Unable to hit dribbble endpoint: " + url, e); } return null; }
From source file:org.auraframework.integration.test.util.AuraHttpTestCase.java
/** * Given a URL to post a GET request, this method compares the actual status code of the response with an expected * status code./*from www . j ava 2s . c o m*/ * * @param msg Error message that should be displayed if the actual response does not match the expected response * @param url URL to be used to execute the GET request * @param statusCode expected status code of response * @throws Exception */ protected void assertUrlResponse(String msg, String url, int statusCode) throws Exception { HttpGet get = obtainGetMethod(new URI(null, url, null).toString()); HttpResponse httpResponse = perform(get); EntityUtils.consume(httpResponse.getEntity()); get.releaseConnection(); int status = getStatusCode(httpResponse); assertEquals(msg, statusCode, status); }
From source file:org.mahasen.client.Download.java
/** * @param fileName//from w w w . j a v a 2 s.co m * @throws IOException */ public void download(String fileName) throws IOException, MahasenClientException, URISyntaxException { httpclient = new DefaultHttpClient(); OutputStream outputStream = null; ClientConfiguration clientConfiguration = ClientConfiguration.getInstance(); try { String userName = clientLoginData.getUserName(); String passWord = clientLoginData.getPassWord(); String hostAndPort = clientLoginData.getHostNameAndPort(); String userId = clientLoginData.getUserId(userName, passWord); Boolean isLogged = clientLoginData.isLoggedIn(); System.out.println(" Is Logged : " + isLogged); if (isLogged == true) { httpclient = WebClientSSLWrapper.wrapClient(httpclient); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("fileName", fileName)); URI uri = URIUtils.createURI("https", hostAndPort, -1, "/mahasen/download_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpPost httppost = new HttpPost(uri); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity httpEntity = response.getEntity(); if (httpEntity.getContentLength() > 0) { outputStream = new FileOutputStream(clientConfiguration.getDownloadRepo() + "/" + fileName); httpEntity.writeTo(outputStream); } else { System.out.println("no content available"); } System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (httpEntity != null) { System.out.println("Response content length: " + httpEntity.getContentLength()); System.out.println("Chunked?: " + httpEntity.isChunked()); } EntityUtils.consume(httpEntity); if (response.getStatusLine().getStatusCode() == 900) { throw new MahasenClientException(String.valueOf(response.getStatusLine())); } } else { System.out.println("User has to be logged in to perform this function"); } } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java
private URI send(final Object message) throws Exception { final FaxRequest request = (FaxRequest) message; final String to = request.to(); final File file = request.file(); // Prepare the request. final DefaultHttpClient client = new DefaultHttpClient(); final HttpContext context = new BasicHttpContext(); final SSLSocketFactory sockets = new SSLSocketFactory(strategy); final Scheme scheme = new Scheme("https", 443, sockets); client.getConnectionManager().getSchemeRegistry().register(scheme); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password); final HttpPost post = new HttpPost(url + to); final String mime = URLConnection.guessContentTypeFromName(file.getName()); final FileEntity entity = new FileEntity(file, mime); post.addHeader(new BasicScheme().authenticate(credentials, post, context)); post.setEntity(entity);//from w w w .java 2 s .co m // Handle the response. final HttpResponse response = client.execute(post, context); final StatusLine status = response.getStatusLine(); final int code = status.getStatusCode(); if (HttpStatus.SC_CREATED == code) { EntityUtils.consume(response.getEntity()); final Header[] headers = response.getHeaders(HttpHeaders.LOCATION); final Header location = headers[0]; final String resource = location.getValue(); return URI.create(resource); } else { final StringBuilder buffer = new StringBuilder(); buffer.append(code).append(" ").append(status.getReasonPhrase()); throw new FaxServiceException(buffer.toString()); } }
From source file:com.ibm.watson.app.common.util.rest.HttpStatusAwareResponseHandler.java
/** * Handle the response. This method is invoked after we have considered it valid. * @param response/*w w w .j ava2 s . c o m*/ * @return T The value to return from the response * @throws IOException if an IOException */ protected T doHandleResponse(HttpResponse response) throws IOException { final HttpEntity entity = response.getEntity(); try { return handleEntity(entity); } catch (IOException e) { // By contract, let the implementation handle this exception throw e; } catch (Exception e) { logger.error(MessageKey.AQWEGA04000E_error_while_handling_resoinse_entity_1.getMessage(e.getMessage())); logger.catching(e); return getDefaultReturnValue(); } finally { EntityUtils.consume(entity); } }
From source file:de.tu_dortmund.ub.data.util.TPUUtil.java
public static String writeResultToFile(final CloseableHttpResponse httpResponse, final Properties config, final String exportDataModelID, final String fileEnding) throws IOException, TPUException { LOG.info("try to write result to file"); final String persistInFolderString = config.getProperty(TPUStatics.PERSIST_IN_FOLDER_IDENTIFIER); final boolean persistInFolder = Boolean.parseBoolean(persistInFolderString); final HttpEntity entity = httpResponse.getEntity(); final String fileName; if (persistInFolder) { final InputStream responseStream = entity.getContent(); final BufferedInputStream bis = new BufferedInputStream(responseStream, 1024); final String resultsFolder = config.getProperty(TPUStatics.RESULTS_FOLDER_IDENTIFIER); fileName = resultsFolder + File.separatorChar + EXPORT_FILE_NAME_PREFIX + exportDataModelID + DOT + fileEnding;// www . java 2 s . c o m LOG.info(String.format("start writing result to file '%s'", fileName)); final FileOutputStream outputStream = new FileOutputStream(fileName); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); IOUtils.copy(bis, bufferedOutputStream); bufferedOutputStream.flush(); outputStream.flush(); bis.close(); responseStream.close(); bufferedOutputStream.close(); outputStream.close(); checkResultForError(fileName); } else { fileName = "[no file name available]"; } EntityUtils.consume(entity); return fileName; }