List of usage examples for org.apache.http.impl.client HttpClientBuilder create
public static HttpClientBuilder create()
From source file:coolmapplugin.util.HTTPRequestUtil.java
public static boolean executeDelete(String targetURL) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpDelete request = new HttpDelete(targetURL); HttpResponse result = httpClient.execute(request); if (result.getStatusLine().getStatusCode() == 500) { return false; }//from www . j a v a 2 s. co m } catch (IOException e) { return false; } return true; }
From source file:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry, String accessToken) throws IOException, UnsupportedRequestVerbException { if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) { throw new UnsupportedRequestVerbException(); }//w w w .j a v a2 s. c o m if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request; switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } ((HttpEntityEnclosingRequestBase) request) .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); request.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String url = BASE_URL + method; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); conn.addRequestProperty("Content-Type", "application/json"); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:simulation.LoadBalancer.java
private void pulseNextGroup() { try {// w w w . j a va2 s .co m ArrayList<SimVehicle> vehicles = new ArrayList<>(); vehicles.addAll(vehicleLists.get(pulseGroup)); for (SimVehicle v : vehicles) { String httpPost = "http://192.168.24.120:8080/pol?license_plate=" + v.getVehicle().getID() + "&lat=" + v.getLocation().getY() + "&lng=" + v.getLocation().getX() + "×tamp=" + v.getTimestamp(); try { HttpUriRequest request = new HttpPost(httpPost); HttpClientBuilder.create().build().execute(request); } catch (IOException e) { e.printStackTrace(); System.out.println(e); } } } catch (Throwable t) { t.printStackTrace(); } System.out.println("Group pulsed:" + pulseGroup + " Amount of cars:" + vehicleLists.get(pulseGroup).size()); vehicleLists.get(pulseGroup).clear(); if (pulseGroup < 14) { pulseGroup++; } else { pulseGroup = 0; } }
From source file:groovesquid.GetAdsThread.java
public static String getFile(String url) { String responseContent = null; HttpEntity httpEntity = null;//from ww w . j a va 2 s . c o m try { HttpGet httpGet = new HttpGet(url); httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); httpGet.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse httpResponse = httpClient.execute(httpGet); ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity.writeTo(baos); } else { throw new RuntimeException(url); } responseContent = baos.toString("UTF-8"); } catch (Exception ex) { log.log(Level.SEVERE, null, ex); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException ex) { log.log(Level.SEVERE, null, ex); } } return responseContent; }
From source file:org.wso2.security.tools.dependencycheck.scanner.NotificationManager.java
private static void notifyStatus(String path, boolean status) throws NotificationManagerException { int i = 0;/*from w ww .j a v a 2s.c om*/ while (i < 10) { try { URI uri = (new URIBuilder()).setHost(automationManagerHost).setPort(automationManagerPort) .setScheme("http").setPath(path).addParameter("containerId", myContainerId) .addParameter("status", String.valueOf(status)).build(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(uri); HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("Notified successfully"); return; } else { i++; } Thread.sleep(2000); } catch (URISyntaxException | InterruptedException | IOException e) { LOGGER.error("Error occurred while notifying the status to automation manager", e); i++; } } throw new NotificationManagerException("Error occurred while notifying status to Automation Manager"); }
From source file:hobbyshare.testclient.RestService_TestClient.java
public void test_GetUserProfile() { HttpClient httpClient = HttpClientBuilder.create().build(); try {// w w w . j a v a2 s . c o m HttpGet request = new HttpGet("http://localhost:8095/get_User?userID=1"); HttpResponse response = httpClient.execute(request); System.out.println("---Testing getUserProfile----"); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); System.out.println("---End of getUserProfile test----"); } catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.nuxeo.directory.connector.json.akeneo.AkeneoInMemoryConnector.java
@Override protected JsonNode call(String url) { String proxyHost = params.get("proxyHost"); String proxyPort = params.get("proxyPort"); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); HttpResponse response;//from w ww .j a v a 2s.c o m StringBuffer productListBuffer = new StringBuffer(); try { response = httpClient.execute(getRequest); } catch (Exception e1) { throw new NuxeoException("Error while getting response", e1); } try { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { productListBuffer.append(output); } return getMapper().readTree(productListBuffer.toString()); } catch (Exception e) { throw new NuxeoException("Error while reading JSON response", e); } }
From source file:com.jaeksoft.searchlib.remote.UriHttp.java
protected UriHttp() { final int timeOut = 30; requestConfig = RequestConfig.custom().setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000) .build();/* ww w. j a v a2s. co m*/ httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); }
From source file:org.sonatype.nexus.httpclient.HttpClientPlan.java
public HttpClientPlan() { this.client = HttpClientBuilder.create(); this.connection = ConnectionConfig.copy(ConnectionConfig.DEFAULT); this.socket = SocketConfig.copy(SocketConfig.DEFAULT); this.request = RequestConfig.copy(RequestConfig.DEFAULT); this.headers = new HashMap<>(); this.attributes = new HashMap<>(); }