List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.skfiy.typhon.spi.auth.p.QihooAuthenticator.java
@Override public UserInfo authentic(OAuth2 oauth) { CloseableHttpClient hc = HC_BUILDER.build(); HttpPost httpPost = new HttpPost("https://openapi.360.cn/user/me"); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("access_token", oauth.getCode())); try {/*from w w w . j a va2 s.co m*/ httpPost.setEntity(new UrlEncodedFormEntity(nvps)); JSONObject json = hc.execute(httpPost, new ResponseHandler<JSONObject>() { @Override public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException { String str = StreamUtils.copyToString(response.getEntity().getContent(), StandardCharsets.UTF_8); return JSON.parseObject(str); } }); if (json.containsKey("error_code")) { throw new OAuth2Exception(json.getString("error_code")); } UserInfo info = new UserInfo(); info.setUsername(getPlatform().getLabel() + "-" + json.getString("name")); info.setPlatform(getPlatform()); return info; } catch (IOException ex) { throw new OAuth2Exception("qihoo?", ex); } finally { try { hc.close(); } catch (IOException ex) { } } }
From source file:com.cognifide.aet.proxy.RestProxyServer.java
@Override public void addHeader(String name, String value) { CloseableHttpClient httpClient = HttpClients.createSystem(); try {/* ww w . jav a2 s . c o m*/ URIBuilder uriBuilder = new URIBuilder().setScheme(HTTP).setHost(server.getAPIHost()) .setPort(server.getAPIPort()); // Request BMP to add header HttpPost request = new HttpPost( uriBuilder.setPath(String.format("/proxy/%d/headers", server.getProxyPort())).build()); request.setHeader("Content-Type", "application/json"); JSONObject json = new JSONObject(); json.put(name, value); request.setEntity(new StringEntity(json.toString())); // Execute request CloseableHttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != STATUS_CODE_OK) { throw new UnableToAddHeaderException( "Invalid HTTP Response when attempting to add header" + statusCode); } response.close(); } catch (Exception e) { throw new BMPCUnableToConnectException(String.format("Unable to connect to BMP Proxy at '%s:%s'", server.getAPIHost(), server.getAPIPort()), e); } finally { try { httpClient.close(); } catch (IOException e) { LOGGER.warn("Unable to close httpClient", e); } } }
From source file:net.maritimecloud.identityregistry.utils.KeycloakAdminUtil.java
/** * Helper function to GET from keycloak api that isn't supported by the client * * @param url The url to GET/*from w w w . j a va 2 s . c om*/ * @param token The access_token to use for identification * @return Returns a string representation of the result */ private String getFromKeycloak(String url, String token) { CloseableHttpClient client = HttpClientBuilder.create().build(); try { log.debug("get url: " + url); HttpGet get = new HttpGet(url); get.addHeader("Authorization", "Bearer " + token); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { log.debug("" + response.getStatusLine().getStatusCode()); return null; } String content = getContent(response.getEntity()); return content; } catch (IOException e) { throw new RuntimeException(e); } } finally { try { client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.cht.imserver.push.TLPushNotification.java
public static PNResult pushMessage_Android(String token, String message, String sender, String licenseKey, PNServerType type, String proxy, int port) throws IOException, UnsupportedEncodingException, ClientProtocolException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpHost httpproxy = null;//from w w w . j ava 2 s . co m String serverURL = null; PNResult result = null; if (type == PNServerType.android_dev) { serverURL = devAndroidHost; } else if (type == PNServerType.android_official) { serverURL = officialAndroidHost; } String jsontoken = "{\"androidTokens\":[{\"token\":\"" + token + "\"}]}"; String jsonmessage = "{\"sender\":\"" + sender + "\",\"message\":\"" + message + "\"}"; //System.out.println("androiddata=" + jsonmessage); //System.out.println("androidtoken=" + jsontoken); //logger.info("jsonmessage:" + jsonmessage + ", jsontoken:" + jsontoken + ", licenseKey:" + licenseKey ); logger.info("jsonmessage:" + jsonmessage + ", licenseKey:" + licenseKey); try { HttpPost httpPost = new HttpPost(serverURL); if (proxy != null) { httpproxy = new HttpHost(proxy, port); RequestConfig config = RequestConfig.custom().setProxy(httpproxy).build(); httpPost.setConfig(config); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("androiddata", jsonmessage)); nvps.add(new BasicNameValuePair("androidtoken", jsontoken)); nvps.add(new BasicNameValuePair("licensekey", licenseKey)); nvps.add(new BasicNameValuePair("appname", appname)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); //System.out.println(EntityUtils.toString(httpPost.getEntity()) ); CloseableHttpResponse response2 = httpclient.execute(httpPost); Gson mGson = new Gson(); try { //System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); //System.out.println(EntityUtils.toString(entity2)); result = mGson.fromJson(EntityUtils.toString(entity2), PNResult.class); EntityUtils.consume(entity2); } finally { response2.close(); } } finally { httpclient.close(); } return result; }
From source file:fi.aalto.drumbeat.drumbeatUI.DrumbeatFileHandler.java
public void receiveFileFromURL(String url_string) { if (url_string == null || url_string.length() == 0) { return;/*from w ww . j ava 2 s . c om*/ } if (!url_string.toLowerCase().endsWith(".ifc")) { Notification n = new Notification("The file extension has to be .ifc", " ", Notification.Type.ERROR_MESSAGE); n.setDelayMsec(5000); n.show(Page.getCurrent()); return; } CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url_string); HttpResponse response; String urlfile = null; if (url_string != null) { urlfile = url_string.substring(url_string.lastIndexOf('/') + 1, url_string.length()); } if (urlfile == null) { return; } try { response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); File targetFile = new File(uploads + urlfile); OutputStream outputStream = new FileOutputStream(targetFile); IOUtils.copy(inputStream, outputStream); outputStream.close(); } } catch (Exception e) { e.printStackTrace(); Notification n = new Notification("Could not read the URL: ", e.getMessage(), Notification.Type.ERROR_MESSAGE); n.setDelayMsec(5000); n.show(Page.getCurrent()); return; } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } File readyFile = new File(uploads + urlfile); if (readyFile.exists()) handleNewFile(readyFile); }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Checks if is ready.// w w w . j a v a 2s.c o m * * @param endPoint the end point * @param testId the test id * @param client the client (optional) * @return true, if is ready * @throws Exception */ public static boolean isReady(String endPoint, String testId, CloseableHttpClient client) throws Exception { if (testId == null) { return false; } boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId + "/progress"); 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); // Completed when estimated number of Test Steps is equal to completed Test Steps // Somehow this condition is necessary but not sufficient // so another check on real value of test is evaluated return jsonRoot.getInt("val") == jsonRoot.getInt("max") & InspireValidatorUtils.isPassed(endPoint, testId, client) != 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 (NotFoundException e) { throw e; } 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 false; }
From source file:kmi.taa.core.SPARQLHTTPClient.java
public String httpGet(String url, String proxy) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); String responseBody;/*ww w .j a v a 2 s. c o m*/ try { if (!proxy.isEmpty()) { String[] str = proxy.split(":"); int port = Integer.parseInt(str[1]); HttpHost host = new HttpHost(str[0], port, str[2]); RequestConfig config = RequestConfig.custom().setProxy(host).build(); httpget.setConfig(config); } 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) { try { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : null; } catch (ClientProtocolException e) { return ""; } } return ""; } }; responseBody = httpclient.execute(httpget, responseHandler); } finally { httpclient.close(); } return responseBody; }
From source file:io.uploader.drive.drive.largefile.DriveAuth.java
public boolean updateAccessToken() throws UnsupportedEncodingException, IOException { // If a refresh_token is set, this class tries to retrieve an access_token. // If refresh_token is no longer valid it resets all tokens to an empty string. if (refreshToken.isEmpty() || accessToken.isEmpty()) { accessToken = config.getCredential().getAccessToken(); tokenType = ""; refreshToken = config.getCredential().getRefreshToken(); }/*from ww w . ja v a2s . c o m*/ logger.info("Updating access_token from Google"); CloseableHttpClient httpclient = getHttpClient(); HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("client_id", clientId)); nvps.add(new BasicNameValuePair("client_secret", clientSecret)); nvps.add(new BasicNameValuePair("refresh_token", refreshToken)); nvps.add(new BasicNameValuePair("grant_type", "refresh_token")); BufferedHttpEntity postentity = new BufferedHttpEntity(new UrlEncodedFormEntity(nvps)); httpPost.setEntity(postentity); CloseableHttpResponse response = httpclient.execute(httpPost); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); boolean tokensOK = false; try { if (response.getStatusLine().getStatusCode() == 200 && entity != null) { String retSrc = EntityUtils.toString(entity); JSONObject result = new JSONObject(retSrc); accessToken = result.getString("access_token"); tokenType = result.getString("token_type"); tokensOK = true; } } finally { response.close(); } httpclient.close(); if (!tokensOK) { refreshToken = ""; accessToken = ""; tokenType = ""; } return tokensOK; }
From source file:com.burakgon.gcmsender.GCMSenderUI.java
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead try {/*from www . java 2 s . c o m*/ HttpPost request = new HttpPost("https://gcm-http.googleapis.com/gcm/send"); JSONObject json = new JSONObject(); StringEntity params = new StringEntity( "{ \"notification\": { \"title\":" + "\"" + notificationTitleText.getText() + "\"" + ", \"text\":" + "\"" + notificationMessageText.getText() + "\"" + "}, \"to\" :" + "\"" + toDevice.getText() + "\"" + "}"); request.addHeader("content-type", "application/json"); request.addHeader("authorization", "key=" + gcmAPIText.getText()); StringEntity se = new StringEntity(json.toString()); request.setEntity(params); HttpResponse response = httpClient.execute(request); resultText.setText(response.getStatusLine().toString()); // handle response here... } catch (Exception ex) { // handle exception here Logger.getLogger(GCMSenderUI.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpClient.close(); } catch (IOException ex) { Logger.getLogger(GCMSenderUI.class.getName()).log(Level.SEVERE, null, ex); } } }