List of usage examples for org.apache.http.impl.client HttpClientBuilder create
public static HttpClientBuilder create()
From source file:com.ge.predix.integration.test.ACSCorsFilterIT.java
@BeforeClass public void setup() throws JsonParseException, JsonMappingException, IOException { if (!Arrays.asList(this.env.getActiveProfiles()).contains("public")) { this.zacTestUtil.assumeZacServerAvailable(); }/*from www. j a v a2s . c o m*/ client = HttpClientBuilder.create().useSystemProperties().build(); }
From source file:eu.skillpro.ams.pscm.connector.amsservice.ui.SendExecutableSkillToServer.java
public static Report push(String id, String snippet, String seeID) throws IOException { String serviceName = "registerResourceExecutableSkill"; StringBuilder parameters = new StringBuilder(); if (id != null && !id.trim().isEmpty()) { parameters.append("?id=" + URLEncoder.encode(id, "UTF-8")); }/*w w w . j a v a 2s.c om*/ if (seeID != null && !seeID.trim().isEmpty()) { parameters.append("&seeID=" + URLEncoder.encode(seeID, "UTF-8")); } if (snippet != null && !snippet.trim().isEmpty()) { parameters.append("&amlDescription=" + URLEncoder.encode(snippet, "UTF-8")); } HttpGet request = new HttpGet(AMSServiceUtility.serviceAddress + serviceName + parameters.toString()); System.out.println(request.getRequestLine() + " ====================================="); request.setHeader("Content-type", "application/json"); HttpClient client = HttpClientBuilder.create().build(); ; HttpResponse response = client.execute(request); System.out.println("Response status: " + response.getStatusLine().getStatusCode()); String resp = EntityUtils.toString(response.getEntity()); Report result = JSONUtility.convertToObject(resp, Report.class); return result; }
From source file:org.ballerinalang.composer.service.tryit.service.HttpTryItClient.java
/** * {@inheritDoc}// w w w. j ava 2 s . c o m */ @Override public String execute() throws TryItException { try { HttpClient client = HttpClientBuilder.create().build(); HttpCoreContext localContext = new HttpCoreContext(); // Create url for the request. String requestUrl = this.buildUrl(); String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString(); switch (httpMethod.toLowerCase(Locale.getDefault())) { case "get": case "delete": case "options": case "head": case "trace": HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long start = System.currentTimeMillis(); // Executing the request. HttpResponse response = client.execute(httpRequest, localContext); long elapsed = System.currentTimeMillis() - start; return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl, elapsed); default: HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase( httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpEntityRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getEntityHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpEntityRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the body of the request. StringEntity postEntity = new StringEntity( this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString()); httpEntityRequest.setEntity(postEntity); // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long entityRequestStart = System.currentTimeMillis(); // Executing the request. HttpResponse entityResponse = client.execute(httpEntityRequest, localContext); long entityRequestDuration = System.currentTimeMillis() - entityRequestStart; return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl, entityRequestDuration); } } catch (IOException e) { throw new TryItException(e.getMessage()); } }
From source file:org.ballerinalang.composer.service.workspace.tryit.HttpTryItClient.java
/** * {@inheritDoc}//from w w w .jav a 2 s . c om */ @Override public String execute() throws TryItException { try { HttpClient client = HttpClientBuilder.create().build(); HttpCoreContext localContext = new HttpCoreContext(); // Create url for the request. String requestUrl = this.buildUrl(); String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString(); switch (httpMethod.toLowerCase(Locale.getDefault())) { case "get": case "delete": case "options": case "head": case "trace": HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long start = System.currentTimeMillis(); // Executing the request. HttpResponse response = client.execute(httpRequest, localContext); long elapsed = System.currentTimeMillis() - start; return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl, elapsed); default: HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase( httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpEntityRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getEntityHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpEntityRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the body of the request. StringEntity postEntity = new StringEntity( this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString()); httpEntityRequest.setEntity(postEntity); // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long entityRequestStart = System.currentTimeMillis(); // Executing the request. HttpResponse entityResponse = client.execute(httpEntityRequest, localContext); long entityRequestDuration = System.currentTimeMillis() - entityRequestStart; return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl, entityRequestDuration); } } catch (java.io.IOException e) { throw new TryItException(e.getMessage()); } }
From source file:br.cefetrj.sagitarii.nunki.comm.WebClient.java
public String doGet(String action, String parameter) throws Exception { String result = "NO_ANSWER"; String mhpHost = gf.getHostURL(); String url = mhpHost + "/" + action + "?" + parameter; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); /*//from w ww. ja v a 2s. c o m if ( gf.useProxy() ) { if ( gf.getProxyInfo() != null ) { HttpHost httpproxy = new HttpHost( gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort() ); httpClient.getCredentialsProvider().setCredentials( new AuthScope( gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort() ), new UsernamePasswordCredentials( gf.getProxyInfo().getUser(), gf.getProxyInfo().getPassword() )); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy); } } */ HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); getRequest.addHeader("Content-Type", "plain/text; charset=utf-8"); getRequest.setHeader("User-Agent", "TaskManager Node"); HttpResponse response = httpClient.execute(getRequest); response.setHeader("Content-Type", "plain/text; charset=UTF-8"); int stCode = response.getStatusLine().getStatusCode(); if (stCode != 200) { // Error } else { HttpEntity entity = response.getEntity(); InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8"); result = convertStreamToString(isr); Charset.forName("UTF-8").encode(result); isr.close(); } httpClient.close(); return result; }
From source file:org.ado.biblio.desktop.server.ServerStatusService.java
@Override protected Task<ServerStatusEnum> createTask() { return new Task<ServerStatusEnum>() { @Override/* ww w . j a v a 2 s.com*/ protected ServerStatusEnum call() throws Exception { final String requestUrl = String.format(SERVER_URL, AppConfiguration.getConfigurationProperty("server.url"), "status"); try { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(requestUrl); HttpResponse response = client.execute(request); LOGGER.info("Response code [{}]", response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return ServerStatusEnum.OFFLINE; } return getServerStatus(IOUtils.toString(response.getEntity().getContent())); } catch (IOException | IllegalStateException e) { return ServerStatusEnum.OFFLINE; } } private ServerStatusEnum getServerStatus(String responseContent) { return new Gson().fromJson(responseContent, ServerStatusMessage.class).getServerStatusEnum(); } }; }
From source file:com.hpe.caf.worker.datastore.cs.KeycloakClient.java
/** * Gets access token./*from w w w. j av a 2 s .co m*/ * * @return the access token * @throws IOException if access token retrieval failed. */ public String getAccessToken() throws IOException { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpPost post = new HttpPost(KeycloakUriBuilder .fromUri(String.format("https://%s:%d/auth", configuration.getServerName(), configuration.getPort())) .path(ServiceUrlConstants.TOKEN_PATH).build(configuration.getRealm())); List<NameValuePair> formparams = new ArrayList<>(); formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, "password")); formparams.add(new BasicNameValuePair("username", configuration.getUserName())); formparams.add(new BasicNameValuePair("password", configuration.getPassword())); String authorization = BasicAuthHelper.createHeader(configuration.getClientName(), configuration.getClientSecret()); post.setHeader("Authorization", authorization); UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(form); LOG.debug("About to request authentication token."); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); LOG.debug("Authentication token response received. Status code: " + status); HttpEntity entity = response.getEntity(); if (status != 200) { String content = IOUtils.toString(entity.getContent()); LOG.error("Failed to retrieve authentication token. Status code:" + status + ". Response content: " + content); throw new IOException("Bad status: " + status + ". Content: " + content); } if (entity == null) { throw new IOException("No Entity"); } try (InputStream is = entity.getContent()) { AccessTokenResponse tokenResponse = JsonSerialization.readValue(is, AccessTokenResponse.class); return tokenResponse.getToken(); } } }
From source file:fi.helsinki.cs.iot.hub.api.handlers.applications.ApplicationGetRequestHandler.java
@Override public Response handleRequest(IotHubRequest uri) { Log.d(TAG, "Got a request"); // Case where we just want to list the libraires if (uri.getIdentifiers().size() == 0) { //Quick try for executing javascript code HttpClient httpclient = HttpClientBuilder.create().build(); // Prepare a request object HttpGet httpget = new HttpGet("http://localhost:8080/libraries/test_jsoo.js"); // Execute the request HttpResponse response;// www.j av a2 s. co m try { response = httpclient.execute(httpget); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); String result = convertStreamToString(instream); DuktapeJavascriptEngineWrapper wrapper = new DuktapeJavascriptEngineWrapper(libdir); wrapper.runScript(result); instream.close(); } } catch (Exception e) { getResponseKo("TODO", e.getMessage()); } return getResponseOk(""); } else if (uri.getIdentifiers().size() == 1) { //Quick try for executing javascript code HttpClient httpclient = HttpClientBuilder.create().build(); // Prepare a request object HttpGet httpget = new HttpGet("http://localhost:8080/libraries/" + uri.getIdentifiers().get(0)); // Execute the request HttpResponse response; try { response = httpclient.execute(httpget); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); String result = convertStreamToString(instream); DuktapeJavascriptEngineWrapper wrapper = new DuktapeJavascriptEngineWrapper(libdir); wrapper.runScript(result); instream.close(); } } catch (Exception e) { getResponseKo("TODO", e.getMessage()); } return getResponseOk("Run is finished"); } else { return getResponseKo(STATUS_NOT_YET_IMPLEMENTED, STATUS_NOT_YET_IMPLEMENTED); } }
From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java
public HttpProxyImpl() { httpClient = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager()) .build(); }
From source file:com.esri.geoportal.commons.http.BotsHttpClient.java
public BotsHttpClient(Bots bots) { this.client = HttpClientBuilder.create().build(); this.bots = bots; }