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.springframework.xd.distributed.util.ServerProcessUtils.java
/** * Block the executing thread until the admin server is responding to * HTTP requests./*from www . j av a 2 s .c o m*/ * * @param url URL for admin server * @throws InterruptedException if the executing thread is interrupted * @throws java.lang.IllegalStateException if a successful connection to the * admin server was not established */ private static void waitForAdminServer(String url) throws InterruptedException, IllegalStateException { boolean connected = false; Exception exception = null; int httpStatus = 0; long expiry = System.currentTimeMillis() + 30000; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try { do { try { Thread.sleep(100); HttpGet httpGet = new HttpGet(url); httpStatus = httpClient.execute(httpGet).getStatusLine().getStatusCode(); if (httpStatus == HttpStatus.SC_OK) { connected = true; } } catch (IOException e) { exception = e; } } while ((!connected) && System.currentTimeMillis() < expiry); } finally { try { httpClient.close(); } catch (IOException e) { // ignore exception on close } } if (!connected) { StringBuilder builder = new StringBuilder(); builder.append("Failed to connect to '").append(url).append("'"); if (httpStatus > 0) { builder.append("; last HTTP status: ").append(httpStatus); } if (exception != null) { StringWriter writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); builder.append("; exception: ").append(exception.toString()).append(", ").append(writer.toString()); } throw new IllegalStateException(builder.toString()); } }
From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java
/** * Gets the response.//from ww w . j a v a2 s. co m * * @param url the url * @param httpClient the http client * @return the response */ public static synchronized HttpResponse getResponse(final String url, final CloseableHttpClient httpClient) { try { checkHTTPClient(httpClient); final HttpGet httpPost = new HttpGet(url); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); httpPost.setHeader(HttpHeaders.ACCEPT, "application/json"); final CloseableHttpResponse response = httpClient.execute(httpPost); setLogString("Status == " + response.getStatusLine(), true); return response; } catch (IOException | HTTPClientException e) { setLogString("Error executing HTTPS method. Reason ::: " + e, true); return null; } }
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by post method./*from w w w . j a v a 2 s.co m*/ * * @param uri: * http://ip:port/demo */ public static String doPostJson(String uri, String data) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setEntity(new StringEntity(data, ContentType.create("text/json", "UTF-8"))); client = HttpClients.createDefault(); response = client.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do post json request has error, msg is " + e.getMessage()); } return result; }
From source file:cn.mrdear.pay.util.WebUtils.java
/** * ?// w w w .j a v a 2s . c o m * @param certPath ? * @param passwd ?? * @param uri ? * @param entity xml * @return */ public static String post(String certPath, String passwd, String uri, InputStreamEntity entity) throws Exception { String result = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File(certPath)); try { keyStore.load(instream, passwd.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httpPost = new HttpPost(uri); entity.setContentEncoding("UTF-8"); httpPost.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPost); result = consumeResponse(httpResponse); } finally { httpclient.close(); } return result; }
From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java
public static Document getUserInfo(HttpGet httpGet, Locale locale) throws IOException, AuthenticatorException, SAXException, ParserConfigurationException { Document userInfo = null;//w ww. jav a 2 s.co m httpGet.setConfig(PassportUtil.StandardRequestConfig); CloseableHttpClient jsonClient = HttpClients.custom().build(); CloseableHttpResponse getResponse = jsonClient.execute(httpGet); String responseString = new BasicResponseHandler().handleResponse(getResponse); if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); userInfo = UtilXml.readXmlDocument(responseString); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), locale); throw new AuthenticatorException(errMsg); } return userInfo; }
From source file:org.apache.vxquery.rest.AbstractRestServerTest.java
/** * Fetch the {@link QueryResultResponse} from query result endpoint once the * corresponding {@link QueryResultRequest} is given. * * @param resultRequest//from w w w .ja v a2s.c om * {@link QueryResultRequest} * @param accepts * expected * * <pre> * Accepts * </pre> * * header in responses * @param method * Http Method to be used to send the request * @return query result response received * @throws Exception */ protected static QueryResultResponse getQueryResultResponse(QueryResultRequest resultRequest, String accepts, String method) throws Exception { URI uri = RestUtils.buildQueryResultURI(resultRequest, restIpAddress, restPort); CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build(); try { HttpUriRequest request = getRequest(uri, method); if (accepts != null) { request.setHeader(HttpHeaders.ACCEPT, accepts); } try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { if (accepts != null) { Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); } Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpResponseStatus.OK.code()); HttpEntity entity = httpResponse.getEntity(); Assert.assertNotNull(entity); String response = RestUtils.readEntity(entity); return RestUtils.mapEntity(response, QueryResultResponse.class, accepts); } } finally { HttpClientUtils.closeQuietly(httpClient); } }
From source file:org.apache.vxquery.rest.AbstractRestServerTest.java
/** * Submit a {@link QueryRequest} and fetth the resulting * {@link AsyncQueryResponse}/*from w w w. ja v a2 s . c o m*/ * * @param uri * uri of the GET request * @param accepts * application/json | application/xml * @param method * Http Method to be used to send the request * @return Response received for the query request * @throws Exception */ protected static <T> T getQuerySuccessResponse(URI uri, String accepts, Class<T> type, String method) throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build(); try { HttpUriRequest request = getRequest(uri, method); if (accepts != null) { request.setHeader(HttpHeaders.ACCEPT, accepts); } try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { Assert.assertEquals(HttpResponseStatus.OK.code(), httpResponse.getStatusLine().getStatusCode()); if (accepts != null) { Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); } HttpEntity entity = httpResponse.getEntity(); Assert.assertNotNull(entity); String response = RestUtils.readEntity(entity); return RestUtils.mapEntity(response, type, accepts); } } finally { HttpClientUtils.closeQuietly(httpClient); } }
From source file:org.jboss.as.test.integration.domain.AbstractSSLMasterSlaveTestCase.java
private static ModelNode executeOverHttp(URI mgmtURI, String operation) throws IOException { CloseableHttpClient httpClient = createHttpClient(mgmtURI); HttpEntity operationEntity = new StringEntity(operation, ContentType.APPLICATION_JSON); HttpPost httpPost = new HttpPost(mgmtURI); httpPost.setEntity(operationEntity); HttpResponse response;/*w ww. ja v a 2s. c o m*/ ModelNode responseNode; try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } responseNode = ModelNode.fromJSONStream(response.getEntity().getContent()); EntityUtils.consume(entity); } finally { httpClient.close(); } return responseNode; }
From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java
private static void closeSelenium1Session(String url, String sessionId) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("cmd", "testComplete")); urlParameters.add(new BasicNameValuePair("sessionId", sessionId)); CloseableHttpClient client = HttpClientBuilder.create().build(); try {// w ww . j a v a 2 s . c om HttpPost request = new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(urlParameters)); client.execute(request); } catch (IOException e) { // ignore silently LOG.debug("Could not execute a POST on url " + url, e); } finally { IOUtils.closeQuietly(client); } }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
protected static Object[] doGet(String url) throws Exception { Object[] response = null;/*from w w w .j a va2 s . c o m*/ if (url == null || url.trim().length() == 0) return response; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { HttpEntity entity1 = response1.getEntity(); String responseBody = responseAsString(response1); int responseStatus = response1.getStatusLine().getStatusCode(); response = new Object[] { responseStatus, responseBody }; // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } return response; }