List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:org.alfresco.selenium.FetchUtil.java
/** * Retrieve file with authentication, using {@link WebDriver} cookie we * keep the session and use HttpClient to download files that requires * user to be authenticated. /* w w w . j av a 2 s . c o m*/ * @param resourceUrl path to file to download * @param driver {@link WebDriver} * @param output path to output the file * @throws IOException if error */ protected static File retrieveFile(final String resourceUrl, final CloseableHttpClient client, final File output) throws IOException { HttpGet httpGet = new HttpGet(resourceUrl); BufferedOutputStream bos = null; BufferedInputStream bis = null; HttpResponse response = null; try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); bos = new BufferedOutputStream(new FileOutputStream(output)); bis = new BufferedInputStream(entity.getContent()); int inByte; while ((inByte = bis.read()) != -1) bos.write(inByte); HttpClientUtils.closeQuietly(response); } catch (Exception e) { logger.error("Unable to fetch file " + resourceUrl, e); } finally { if (response != null) { HttpClientUtils.closeQuietly(response); } if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } return output; }
From source file:org.cloudsimulator.utility.RestAPI.java
private static CloseableHttpResponse postRequestBasicAuth(final CloseableHttpClient httpClient, final String uri, final String username, final String password, final String contentType, final HttpEntity entityToSend) throws IOException { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(CONTENTTYPE, contentType); httpPost.addHeader(AUTHORIZATION, getBasicAuth(username, password)); httpPost.setEntity(entityToSend);/*from w w w . j a v a2 s .c o m*/ return httpClient.execute(httpPost); }
From source file:org.roda.core.util.RESTClientUtility.java
public static <T extends Serializable> T sendPostRequest(T element, Class<T> elementClass, String url, String resource, String username, String password) throws RODAException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String basicAuthToken = new String(Base64.encode((username + ":" + password).getBytes())); HttpPost httpPost = new HttpPost(url + resource); httpPost.setHeader("Authorization", "Basic " + basicAuthToken); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("Accept", "application/json"); try {//from w w w . j a v a2 s .c o m httpPost.setEntity(new StringEntity(JsonUtils.getJsonFromObject(element))); HttpResponse response; response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode == 201) { return JsonUtils.getObjectFromJson(responseEntity.getContent(), elementClass); } else { throw new RODAException("POST request response status code: " + responseStatusCode); } } catch (IOException e) { throw new RODAException("Error sending POST request", e); } }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get.//w w w. j a va 2 s .c o m * * @param uri * the uri * @param headers * the headers * @return the string * @throws ClientProtocolException * the client protocol exception * @throws IOException * Signals that an I/O exception has occurred. * @throws HttpResponseException * the http response exception */ public static HttpGetSimpleResp doGet(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpGet); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future // ResponseHandler<String> handler = new BasicResponseHandler(); resp.setResult(new BasicResponseHandler().handleResponse(response)); } EntityUtils.consume(entity); } finally { response.close(); } } else { // TODO optimiz (repeating code) throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:org.jboss.pnc.auth.client.SimpleOAuthConnect.java
private static String[] connect(String url, Map<String, String> urlParams) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // add header httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>(); for (String key : urlParams.keySet()) { urlParameters.add(new BasicNameValuePair(key, urlParams.get(key))); }/*from w ww . j a va 2 s . c o m*/ httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); CloseableHttpResponse response = httpclient.execute(httpPost); String refreshToken = ""; String accessToken = ""; try { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { if (line.contains("refresh_token")) { String[] respContent = line.split(","); for (int i = 0; i < respContent.length; i++) { String split = respContent[i]; if (split.contains("refresh_token")) { refreshToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1); } if (split.contains("access_token")) { accessToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1); } } } } } finally { response.close(); } return new String[] { accessToken, refreshToken }; }
From source file:DeliverWork.java
private static String saveIntoWeed(RemoteFile remoteFile, String projectId) throws SQLException, UnsupportedEncodingException { String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id=" + URLEncoder.encode(remoteFile.getFileId(), "utf-8"); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String res = ""; try {//from w w w. j a va2s . com httpClient = HttpClients.createSystem(); // http(get?) HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); HttpEntity result = response.getEntity(); String fileName = remoteFile.getFileName(); FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName, new ByteArrayInputStream(EntityUtils.toByteArray(result))); System.out.println(fileHandleStatus); File file = new File(); if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) { file.setContentType(result.getContentType().getValue()); } else { file.setContentType("application/error"); } file.setDataId(Integer.parseInt(projectId)); file.setName(fileName); if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png") || fileName.contains(".gif")) { file.setType(1); } else if (fileName.contains(".doc") || fileName.contains(".docx")) { file.setType(2); } else if (fileName.contains(".xlsx") || fileName.contains("xls")) { file.setType(3); } else if (fileName.contains(".pdf")) { file.setType(4); } else { file.setType(5); } String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName); file.setUrl(accessUrl); file.setSize(fileHandleStatus.getSize()); file.setPostTime(new java.util.Date()); file.setStatus(0); file.setEnumValue(findFileType(remoteFile.getFileType())); file.setResources(1); // JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver"); // Connection connection = jdbcFactoryChanye.getConnection(); DatabaseMetaData dmd = connection.getMetaData(); PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" }); ps.setString(1, sdf.format(file.getPostTime())); ps.setInt(2, file.getType()); ps.setString(3, file.getEnumValue()); ps.setInt(4, file.getDataId()); ps.setString(5, file.getUrl()); ps.setString(6, file.getName()); ps.setString(7, file.getContentType()); ps.setLong(8, file.getSize()); ps.setInt(9, file.getStatus()); ps.setInt(10, file.getResources()); ps.executeUpdate(); if (dmd.supportsGetGeneratedKeys()) { ResultSet rs = ps.getGeneratedKeys(); while (rs.next()) { System.out.println(rs.getLong(1)); } } ps.close(); res = "success"; } catch (ClientProtocolException e) { e.printStackTrace(); res = e.getMessage(); } catch (IOException e) { e.printStackTrace(); res = e.getMessage(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return res; }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSignOut(CloseableHttpClient httpClient, String url, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { try {//from ww w .java2 s . co m // logout to service provider HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String parsedEntity = EntityUtils.toString(entity); Assert.assertTrue(parsedEntity.contains("Logout from the following realms")); Source source = new Source(parsedEntity); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } // Now send logout form to IdP nvps.add(new BasicNameValuePair("_eventId_submit", "Logout")); HttpPost httppost = new HttpPost("https://localhost:" + idpPort + "/" + postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); return EntityUtils.toString(entity); } finally { if (httpClient != null) { httpClient.close(); } } }
From source file:org.wuspba.ctams.ws.ITVenueController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (Venue v : doc.getVenues()) { ids.add(v.getId());// w w w .j a v a 2s. c o m } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { 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); } } } } }
From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java
private static void closeSelenium2Session(String originalUrl, String sessionId) { CloseableHttpClient client = HttpClientBuilder.create().build(); String baseUrl = originalUrl + "/wd/hub/session/" + sessionId; try {/*from www . j a va 2 s .c o m*/ HttpGet getMethod = new HttpGet(baseUrl + "/window_handles"); HttpResponse response = client.execute(getMethod); JSONObject result = extractJSONObject(response); if (result != null) { // close all of these windows String url = baseUrl + "/window"; JSONArray array = result.getJSONArray("value"); for (int i = 0; i < array.length(); i++) { // activate this window, and close it JSONObject obj = new JSONObject(); obj.put("name", array.getString(i)); performPost(url, obj.toString()); performDelete(url); } } // now, delete the session performDelete(baseUrl); } catch (IOException e) { // ignore silently } catch (JSONException e) { // ignore silently } finally { IOUtils.closeQuietly(client); } }
From source file:com.vaushell.superpipes.tools.HTTPhelper.java
/** * Load a image./*ww w. j av a 2s. c o m*/ * * @param client Http client. * @param uri the URL. * @return the image. * @throws IOException */ public static BufferedImage loadPicture(final CloseableHttpClient client, final URI uri) throws IOException { if (client == null || uri == null) { throw new IllegalArgumentException(); } HttpEntity responseEntity = null; try { // Exec request final HttpGet get = new HttpGet(uri); try (final CloseableHttpResponse response = client.execute(get)) { final StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 200) { throw new IOException(sl.getReasonPhrase()); } responseEntity = response.getEntity(); final Header ct = responseEntity.getContentType(); if (ct == null) { return null; } final String type = ct.getValue(); if (type == null) { return null; } if (!type.startsWith("image/")) { return null; } try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { try (final InputStream is = responseEntity.getContent()) { IOUtils.copy(is, bos); } if (bos.size() <= 0) { return null; } else { try (final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) { return ImageIO.read(bis); } } } } } finally { if (responseEntity != null) { EntityUtils.consume(responseEntity); } } }