List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Uploads the specified file to the community site. The return identifier * can be used later when composing other requests. * //from w w w. j av a 2 s .com * @param httpclient * the http client * @param attachment * the file to attach * @param authCookie * the session cookie to use for authentication purpose * @return the identifier of the file uploaded, <code>null</code> otherwise * @throws CommunityAPIException */ public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie) throws CommunityAPIException { FileInputStream fin = null; try { fin = new FileInputStream(attachment); byte fileContent[] = new byte[(int) attachment.length()]; fin.read(fileContent); byte[] encodedFileContent = Base64.encodeBase64(fileContent); FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent); HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL); EntityBuilder fileUploadEntity = EntityBuilder.create(); fileUploadEntity.setText(uploadReq.getAsJSON()); fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); fileuploadPOST.setEntity(fileUploadEntity.build()); CloseableHttpResponse resp = httpclient.execute(fileuploadPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$ return fid; } else { CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } } catch (FileNotFoundException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } finally { IOUtils.closeQuietly(fin); } }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Logout to pulse server and close httpClient * To be called from setupAfterClass in each test class *//* w w w . j a v a 2 s .c o m*/ protected static void doLogout() throws Exception { System.out.println("BaseServiceTest :: Executing doLogout with user : admin, password : admin."); if (httpclient != null) { CloseableHttpResponse logoutResponse = null; try { HttpUriRequest logout = RequestBuilder.get().setUri(new URI(LOGOUT_URL)).build(); logoutResponse = httpclient.execute(logout); try { HttpEntity entity = logoutResponse.getEntity(); EntityUtils.consume(entity); } finally { if (logoutResponse != null) logoutResponse.close(); httpclient.close(); httpclient = null; } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogout"); } else { System.out.println("BaseServiceTest :: User NOT logged-in"); } }
From source file:com.wattzap.model.social.SelfLoopsAPI.java
public static int uploadActivity(String email, String passWord, String fileName, String note) throws IOException { JSONObject jsonObj = null;/*from w ww .ja v a 2s. c om*/ FileInputStream in = null; GZIPOutputStream out = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("enctype", "multipart/mixed"); in = new FileInputStream(fileName); // Create stream to compress data and write it to the to file. ByteArrayOutputStream obj = new ByteArrayOutputStream(); out = new GZIPOutputStream(obj); // Copy bytes from one stream to the other byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.close(); in.close(); ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"), fileName); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN)) .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin) .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); switch (code) { case 200: HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); //System.out.println(content); JSONParser jsonParser = new JSONParser(); jsonObj = (JSONObject) jsonParser.parse(content); } break; case 403: throw new RuntimeException( "Authentification failure " + email + " " + response.getStatusLine()); default: throw new RuntimeException("Error " + code + " " + response.getStatusLine()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (response != null) { response.close(); } } int activityId = ((Long) jsonObj.get("activity_id")).intValue(); // parse error code int error = ((Long) jsonObj.get("error_code")).intValue(); if (activityId == -1) { String message = (String) jsonObj.get("message"); switch (error) { case 102: throw new RuntimeException("Empty TCX file " + fileName); case 103: throw new RuntimeException("Invalide TCX Format " + fileName); case 104: throw new RuntimeException("TCX Already Present " + fileName); case 105: throw new RuntimeException("Invalid XML " + fileName); case 106: throw new RuntimeException("invalid compression algorithm"); case 107: throw new RuntimeException("Invalid file mime types"); default: throw new RuntimeException(message + " " + error); } } return activityId; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } httpClient.close(); } }
From source file:tradeok.HttpTool.java
public static String postJsonBody(String url, int timeout, Map<String, Object> map, String encoding) throws Exception { HttpPost post = new HttpPost(url); try {//w ww . j a v a 2 s . c om RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setExpectContinueEnabled(false) .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); post.setConfig(requestConfig); post.setHeader("User-Agent", USER_AGENT); post.setHeader("Accept", "text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Connection", "keep-alive"); post.setHeader("Content-Type", "application/json; charset=UTF-8"); String str1 = object2json(map).replace("\\", ""); post.setEntity(new StringEntity(str1, encoding)); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); try { if (entity != null) { String str = EntityUtils.toString(entity, encoding); return str; } } finally { if (entity != null) { entity.getContent().close(); } } } finally { if (response != null) { response.close(); } } } finally { post.releaseConnection(); } return ""; }
From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java
static void getTokensFromCode() { access_token = null;//from ww w .j a v a 2s .c o m expires_in = -1; token_start_time = -1; refresh_token = null; new File("refresh.txt").delete(); if (gProps == null) { initGProps(); } // Query for token now that user has gone through browser part // of // flow HttpPost tokenRequest = new HttpPost(gProps.token_uri); MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create(); tokenRequestParams.addTextBody("client_id", gProps.client_id); tokenRequestParams.addTextBody("client_secret", gProps.client_secret); tokenRequestParams.addTextBody("code", device_code); tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0"); HttpEntity reqEntity = tokenRequestParams.build(); tokenRequest.setEntity(reqEntity); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { response = httpclient.execute(tokenRequest); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); access_token = root.get("access_token").asText(); refresh_token = root.get("refresh_token").asText(); token_start_time = System.currentTimeMillis() / 1000; expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (response != null) { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
protected static Object[] doGet(String url) throws Exception { Object[] response = null;/*w w w . j a v a 2 s . c o m*/ if (url == null || url.trim().length() == 0) return response; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { HttpEntity entity1 = response1.getEntity(); String responseBody = responseAsString(response1); int responseStatus = response1.getStatusLine().getStatusCode(); response = new Object[] { responseStatus, responseBody }; // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } return response; }
From source file:com.hazelcast.test.starter.HazelcastVersionLocator.java
private static File downloadFile(String url, File targetDirectory, String filename) { CloseableHttpClient client = HttpClients.createDefault(); File targetFile = new File(targetDirectory, filename); if (targetFile.isFile() && targetFile.exists()) { return targetFile; }//w w w . ja va2s. c om HttpGet request = new HttpGet(url); try { CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != SC_OK) { throw new GuardianException("Cannot download file from " + url + ", http response code: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); FileOutputStream fos = new FileOutputStream(targetFile); entity.writeTo(fos); fos.close(); targetFile.deleteOnExit(); return targetFile; } catch (IOException e) { throw rethrowGuardianException(e); } finally { try { client.close(); } catch (IOException e) { // ignore } } }
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageString receiveString(final String restAPIURI, final String username, final String password, final String typeOfString, final String charset) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageString responseMessageString = null; httpResponse = getRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString); if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } else { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); }// ww w .j av a2 s. co m } else { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(null, null, IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } } httpResponse.close(); } httpClient.close(); return responseMessageString; }
From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java
protected static void delete() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", TestFixture.INSTANCE.bandContestEntry.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {/*from w w w . j av a 2 s. co m*/ response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITBandContestController.delete(); ITBandController.delete(); ITVenueController.delete(); ITJudgeController.delete(); }
From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.java
protected static void delete() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", TestFixture.INSTANCE.soloContestEntry.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {// ww w. j a v a2 s. com response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITSoloContestController.delete(); ITPersonController.delete(); ITVenueController.delete(); ITJudgeController.delete(); }