List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) { HttpPost post = null;/*from ww w . j av a 2 s . c om*/ HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); post = new HttpPost(url); File file = new File(fileName); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, fileContentType); mpEntity.addPart("file", cbFile); post.setEntity(mpEntity); post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); //post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data"); post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON); response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testPostWithContentTypeKnox681() throws Exception { LOG_ENTER();/* w w w. jav a 2s . c o m*/ MockServer mock = new MockServer("REPEAT", true); params = new Properties(); params.put("MOCK_SERVER_PORT", mock.getPort()); params.put("LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()); String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("{\"name\":\"value\"}".getBytes()).contentLength(-1) .contentType("application/json; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat"); String uname = "guest"; String pword = uname + "-password"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(uname, pword)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.createDefault(); HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/json"); CloseableHttpResponse response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json; charset=UTF-8")); String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(body, is("{\"name\":\"value\"}")); response.close(); client.close(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("<test-xml/>".getBytes()).contentType("application/xml; charset=UTF-8") .header("Location", gatewayUrl + "/knox681/repeat"); client = HttpClients.createDefault(); request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/xml"); response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8")); body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(the(body), hasXPath("/test-xml")); response.close(); client.close(); mock.stop(); LOG_EXIT(); }
From source file:com.ny.apps.executor.TencentWeiboOAuth2.java
public String getCode(String APPKEY, String APPSECRET) throws Exception { String code = null;/*w ww . j a v a 2 s .c om*/ CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(prepareGetUrl()); System.out.println(prepareGetUrl().toASCIIString()); logger.info("executing request " + httpGet.getURI()); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity); } else { throw new ClientProtocolException("Unexpected response status: " + statusCode); } } }; try { String responseBody = client.execute(httpGet, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } finally { client.close(); } return code; }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Checks if is passed.//from ww w . j a va2 s. c o m * * @param endPoint the end point * @param testId the test id * @param client the client (optional) * @return the string * @throws Exception */ public static String isPassed(String endPoint, String testId, CloseableHttpClient client) throws Exception { if (testId == null) { throw new Exception(""); } boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); try { return jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns") .getJSONObject("TestRun").getString("status"); } catch (JSONException e) { return null; } } else if (response.getStatusLine().getStatusCode() == 404) { throw new NotFoundException("Test not found"); } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress"); } } catch (Exception e) { Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e); throw e; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } return null; }
From source file:es.uned.dia.jcsombria.model_elements.softwarelinks.nodejs.HttpTransport.java
public Object send(String request) throws Exception { Object response = null;//from w w w. ja va 2s . c om CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverURL.toString()); System.out.println("Executing request " + httppost.getRequestLine()); System.out.println(request); httppost.setEntity(new StringEntity(request)); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httppost, responseHandler); response = responseBody; } finally { httpclient.close(); } return response; }
From source file:pl.datamatica.traccar.api.fcm.Daemon.java
private String sendToFcm(String body) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send"); CloseableHttpResponse response = null; try {/*ww w.j a va2 s .c om*/ request.addHeader("Authorization", "key=" + Application.getConfigRecord("java:/fcm_secret")); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(body)); response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) return EntityUtils.toString(response.getEntity()); return EntityUtils.toString(response.getEntity()); } catch (NamingException ne) { // probably config file doesn't have fcm secret Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ne); return null; } catch (Exception ex) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex); return null; } finally { try { if (response != null) response.close(); client.close(); } catch (IOException ex) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.arquillian.droidium.native_.selendroid.SelendroidServerManager.java
/** * Waits for the start of Selendroid server. * * After installation and execution of instrumentation command, we repeatedly send HTTP request to status page to get * response code of 200 - server is up and running and we can proceed safely to testing process. * * @param port port to wait on the communication from installed Selendroid server * @throws InvalidSelendroidPortException if {@code port} is invalid *///from w w w.j ava 2 s . c o m private void waitUntilSelendroidServerCommunication(int port) { validatePort(port); RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT_SECONDS * 1000) .setConnectionRequestTimeout(CONNECTION_TIME_OUT_SECONDS * 1000) .setSocketTimeout(SOCKET_TIME_OUT_SECONDS * 1000).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config) .disableContentCompression().build(); HttpGet httpGet = new HttpGet(getSelendroidStatusURI(port)); boolean connectionSuccess = false; for (int i = NUM_CONNECTION_RETIRES; i > 0; i--) { try { HttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { connectionSuccess = true; break; } logger.log(Level.INFO, i + ": Response was not 200 from port " + port + ", response was: " + statusCode); } catch (ClientProtocolException e) { logger.log(Level.WARNING, e.getMessage()); } catch (IOException e) { logger.log(Level.WARNING, e.getMessage()); } } try { client.close(); } catch (IOException e) { logger.log(Level.WARNING, e.getMessage()); } if (!connectionSuccess) { throw new AndroidExecutionException("Unable to get successful connection from Selendroid http server."); } }
From source file:net.duckling.ddl.util.RESTClient.java
public JsonObject httpGet(String url, List<NameValuePair> params) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/* w ww .ja v a 2s . c o m*/ RequestBuilder rb = RequestBuilder.get().setUri(new URI(url)); for (NameValuePair hp : params) { rb.addParameter(hp.getName(), hp.getValue()); } rb.addHeader("accept", "application/json"); HttpUriRequest uriRequest = rb.build(); HttpResponse response = httpclient.execute(uriRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(br); return je.getAsJsonObject(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { httpclient.close(); } return null; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse get(String url, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w ww. j a v a 2 s .c o m*/ RequestBuilder _reqBuilder = RequestBuilder.get().setUri(url); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:com.code42.demo.RestInvoker.java
/** * Builds and executes an HttpPost Request by appending the urlQuery parameter to the * serverHost:serverPort variables and inserting the contents of the payload parameter. * Returns the data payload response as a JSONObject. * /*from w w w . ja va 2 s . c o m*/ * @param urlQuery * @param payload * @return org.json.simple.JSONObject * @throws Exception */ public JSONObject postAPI(String urlQuery, String payload) throws Exception { HttpClientBuilder hcs; CloseableHttpClient httpClient; hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (ssl) { hcs.setSSLSocketFactory(sslsf); } httpClient = hcs.build(); JSONObject data; StringEntity payloadEntity = new StringEntity(payload, ContentType.APPLICATION_JSON); try { HttpPost httpPost = new HttpPost(ePoint + urlQuery); m_log.info("Executing request : " + httpPost.getRequestLine()); m_log.debug("Payload : " + payload); httpPost.setEntity(payloadEntity); CloseableHttpResponse resp = httpClient.execute(httpPost); try { String jsonResponse = EntityUtils.toString(resp.getEntity()); JSONParser jp = new JSONParser(); JSONObject jObj = (JSONObject) jp.parse(jsonResponse); data = (JSONObject) jObj.get("data"); m_log.debug(data); } finally { resp.close(); } } finally { httpClient.close(); } return data; }