List of usage examples for org.apache.http.impl.client HttpClients createDefault
public static CloseableHttpClient createDefault()
From source file:org.optaconf.service.AbstractClientArquillianTest.java
protected String postAndReadSingleMessage(String url) { InputStream contentIn = null; try {/*from w w w .j a v a 2 s .c o m*/ HttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); contentIn = response.getEntity().getContent(); List<String> lines = IOUtils.readLines(contentIn); assertEquals(1, lines.size()); return lines.get(0); } catch (IOException e) { throw new IllegalStateException("Failed to connect to url (" + url + ").", e); } finally { IOUtils.closeQuietly(contentIn); } }
From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java
@Test public void testListAll() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); LOG.info("Connecting to " + uri.toString()); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); assertEquals(doc.getHiredJudges().size(), 4); EntityUtils.consume(entity);// ww w. j a v a2 s .com } }
From source file:org.craftercms.deployer.impl.processors.HttpMethodCallProcessor.java
@Override protected void doInit(Configuration mainConfig, Configuration processorConfig) throws DeploymentException { url = ConfigurationUtils.getRequiredString(processorConfig, URL_PROPERTY_NAME); method = ConfigurationUtils.getRequiredString(processorConfig, METHOD_PROPERTY_NAME); httpClient = HttpClients.createDefault(); }
From source file:com.mywork.framework.util.RemoteHttpUtil.java
/** * ?? Post/* w w w.ja va 2 s .c o m*/ * @return */ public static String doPost(String contentUrl, Map<String, String> headerMap, String jsonBody) { String result = null; CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(contentUrl); RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_SECONDS * 1000) .setConnectTimeout(TIMEOUT_SECONDS * 1000).setSocketTimeout(TIMEOUT_SECONDS * 1000).build(); post.setConfig(config); try { if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { post.setHeader(m.getKey(), m.getValue()); } } if (jsonBody != null) { StringEntity entity = new StringEntity(jsonBody, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); } long start = System.currentTimeMillis(); response = httpClient.execute(post); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start)); EntityUtils.consume(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java
public BitcoindApiHandler(String host, int port, String protocol, String uri, String username, String password) {/* w ww .j a v a 2s .c o m*/ this.uri = uri; httpClient = HttpClients.createDefault(); targetHost = new HttpHost(host, port, protocol); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); }
From source file:com.partnet.automation.http.ApacheHttpAdapter.java
private Response method(HttpRequestBase httpRequestBase, String contentType, String body) { Response.Builder responseBuilder; if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) { this.setEntity((HttpEntityEnclosingRequestBase) httpRequestBase, contentType, body); }/*from w ww. j ava2 s .c om*/ try (CloseableHttpClient httpclient = HttpClients.createDefault()) { LOG.debug("Executing request " + httpRequestBase.getRequestLine()); if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) { HttpEntity entity = (((HttpEntityEnclosingRequestBase) httpRequestBase).getEntity()); if (entity != null) { LOG.debug("Body being sent: " + EntityUtils.toString(entity)); } } //handle response ResponseHandler<Response.Builder> responseHandler = new ResponseHandler<Response.Builder>() { @Override public Response.Builder handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { Response.Builder rb = new Response.Builder(); if (response.getEntity() != null) { rb.setBody(EntityUtils.toString(response.getEntity())); } rb.setStatusCode(response.getStatusLine().getStatusCode()); rb.setHeaders(convertApacheToHeaderAdapter(response.getAllHeaders())); if (response.getEntity() != null) { rb.setContentType(convertApacheToHeaderAdapter(response.getEntity().getContentType())[0]); } return rb; } }; //handle cookies HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); responseBuilder = httpclient.execute(httpRequestBase, responseHandler, context); responseBuilder.setCookies(convertCookieToAdapter(context.getCookieStore().getCookies())); } catch (IOException e) { throw new IllegalStateException("IOException occurred while attempting to communicate with endpoint", e); } return responseBuilder.build(); }
From source file:com.urswolfer.intellij.plugin.gerrit.errorreport.PluginErrorReportSubmitter.java
private void postError(String json) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(ERROR_REPORT_URL); httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); try {//from w w w . j a v a 2s .c om httpClient.execute(httpPost); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:fi.vm.kapa.identification.client.ProxyClient.java
public ProxyMessageDTO updateSession(Map<String, String> sessionData, String tid, String pid, String logTag) throws InternalErrorException, InvalidRequestException, IOException { String proxyCallUrl = proxyURLBase + tid + "&pid=" + pid; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(proxyCallUrl); postMethod.setHeader(HEADER_TYPE, HEADER_VALUE); Gson gson = new Gson(); postMethod.setEntity(new StringEntity(gson.toJson(sessionData))); HttpContext context = HttpClientContext.create(); CloseableHttpResponse restResponse = httpClient.execute(postMethod, context); ProxyMessageDTO messageDTO = null;/*from ww w. j a v a2 s. c om*/ int statusCode = restResponse.getStatusLine().getStatusCode(); if (statusCode == HTTP_INTERNAL_ERROR) { logger.warn("<<{}>> Proxy encountered internal error", logTag); throw new InternalErrorException(); } else { if (statusCode == HTTP_OK) { messageDTO = gson.fromJson(EntityUtils.toString(restResponse.getEntity()), ProxyMessageDTO.class); } else { logger.warn("<<{}>> Failed to build session, Proxy responded with HTTP {}", logTag, statusCode); throw new InvalidRequestException(); } } restResponse.close(); return messageDTO; }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Check service status.//from w w w . java 2s .c om * * @param endPoint the end point * @param client the client (optional) (optional) * @return true, if successful */ public static boolean checkServiceStatus(String endPoint, CloseableHttpClient client) { boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } HttpGet request = new HttpGet(endPoint + CheckStatus_URL); // add request header request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; try { response = client.execute(request); } catch (Exception e) { Log.warning(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e); return false; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } if (response.getStatusLine().getStatusCode() == 200) { return true; } else { Log.warning(Log.SERVICE, "INSPIRE service not available: " + endPoint + CheckStatus_URL); return false; } }
From source file:org.yql4j.impl.HttpComponentsYqlClient.java
/** * Default constructor. */ public HttpComponentsYqlClient() { this(HttpClients.createDefault()); }