List of usage examples for org.apache.http.impl.client HttpClients createDefault
public static CloseableHttpClient createDefault()
From source file:org.keycloak.authorization.client.Configuration.java
public HttpClient getHttpClient() { if (this.httpClient == null) { this.httpClient = HttpClients.createDefault(); }/*from www .j av a2 s .co m*/ return httpClient; }
From source file:io.tourniquet.junit.http.rules.examples.HttpServerPostResponseStubbingExample.java
@Test public void testHttpServerPost_withParams() throws Exception { //prepare/*www .ja v a 2s.co m*/ server.on(POST).resource("/action.do").withParam("field1", "value1").withParam("field2", "value2") .respond("someContent"); //act try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(post("http://localhost:55555/action.do", param("field1", "value1"), param("field2", "value2")))) { String content = getString(response.getEntity()); assertEquals("someContent", content); } }
From source file:io.joynr.messaging.bounceproxy.ControlledBounceProxyModule.java
@Provides CloseableHttpClient getCloseableHttpClient() { // For now, we provide the httpclient in here, as the configuration is // different from messaging configuration (e.g. no proxy settings). // If a custom configuration is needed, a separate provider should be // created.//w w w. j av a 2s. c o m return HttpClients.createDefault(); }
From source file:org.disit.servicemap.SparqlProxy.java
private void redirectToLog(HttpServletRequest theReq, HttpServletResponse theResp) throws Exception { HttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = null;//from w w w . java2 s.c o m HttpResponse response = null; long startTime = System.nanoTime(); String theServerHost = Configuration.getInstance().get("sparqlEndpoint", null); if (theServerHost == null) theServerHost = "http://192.168.0.207:8890/sparql"; //String aEncodedQuery = URLEncoder.encode(query, "UTF-8"); //String serviceUri = theReq.getParameter("query"); String theReqUrl = theServerHost + "?"; String query = theReq.getParameter("query"); if (query != null) { String aEncodedQuery = URLEncoder.encode(query, "UTF-8"); theReqUrl += "query=" + aEncodedQuery; } String format = theReq.getParameter("format"); if (format != null) theReqUrl += "&format=" + format; try { httpget = new HttpGet(theReqUrl); //System.out.println("request header:"); Enumeration<String> aHeadersEnum = theReq.getHeaderNames(); while (aHeadersEnum.hasMoreElements()) { String aHeaderName = aHeadersEnum.nextElement(); String aHeaderVal = theReq.getHeader(aHeaderName); httpget.setHeader(aHeaderName, aHeaderVal); //System.out.println(" " + aHeaderName + ": " + aHeaderVal); } if (log.isDebugEnabled()) { log.debug("executing request " + httpget.getURI()); } // Create a response handler response = httpclient.execute(httpget); //System.out.println("response header:"); // set the same Headers for (Header aHeader : response.getAllHeaders()) { if (!aHeader.getName().equals("Transfer-Encoding") || !aHeader.getValue().equals("chunked")) { theResp.setHeader(aHeader.getName(), aHeader.getValue()); } //System.out.println(" " + aHeader.getName() + ": " + aHeader.getValue()); } // set the same locale if (response.getLocale() != null) { theResp.setLocale(response.getLocale()); } // set the content theResp.setContentLength((int) response.getEntity().getContentLength()); theResp.setContentType(response.getEntity().getContentType().getValue()); // set the same status theResp.setStatus(response.getStatusLine().getStatusCode()); // redirect the output InputStream aInStream = null; OutputStream aOutStream = null; try { aInStream = response.getEntity().getContent(); aOutStream = theResp.getOutputStream(); byte[] buffer = new byte[1024]; int r = 0; do { r = aInStream.read(buffer); if (r != -1) { aOutStream.write(buffer, 0, r); } } while (r != -1); /* int data = aInStream.read(); while (data != -1) { aOutStream.write(data); data = aInStream.read(); } */ } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (aInStream != null) { aInStream.close(); } if (aOutStream != null) { aOutStream.close(); } } } finally { httpclient.getConnectionManager().closeExpiredConnections(); httpclient.getConnectionManager().shutdown(); } ServiceMap.logQuery(query, "SPARQL", theReq.getRemoteAddr(), theReq.getHeader("User-Agent"), System.nanoTime() - startTime); }
From source file:com.networknt.health.HealthHandlerTest.java
@Test public void testHealth() throws Exception { String url = "http://localhost:8080/server/health"; CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); try {/* w ww.j a v a2s . com*/ CloseableHttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(200, statusCode); if (statusCode == 200) { String s = IOUtils.toString(response.getEntity().getContent(), "utf8"); Assert.assertNotNull(s); Assert.assertEquals("OK", s); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.networknt.audit.ServerInfoHandlerTest.java
@Test public void testServerInfo() throws Exception { String url = "http://localhost:8080/server/info"; CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); try {/*from w w w.j av a 2 s. c o m*/ CloseableHttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(200, statusCode); if (statusCode == 200) { String s = IOUtils.toString(response.getEntity().getContent(), "utf8"); Assert.assertNotNull(s); logger.debug(s); } } catch (Exception e) { e.printStackTrace(); } }
From source file:cn.aofeng.demo.httpclient.HttpClientBasic.java
public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost + "/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity);//from ww w . j a v a 2 s. c o m CloseableHttpResponse response = client.execute(post); processResponse(response); }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
private static File download(File file, URL url) { CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; OutputStream out = null;/*from w w w . j a va2 s . c o m*/ file.getParentFile().mkdirs(); try { HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Builder builder = RequestConfig.custom(); HttpHost proxy = getProxy(target); if (proxy != null) { builder = builder.setProxy(proxy); } RequestConfig config = builder.build(); HttpGet request = new HttpGet(url.toURI()); request.setConfig(config); response = httpclient.execute(target, request); InputStream in = response.getEntity().getContent(); out = new BufferedOutputStream(new FileOutputStream(file)); copy(in, out); return file; } catch (Exception e) { logWarning(e); ; } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (response != null) { try { response.close(); } catch (IOException e) { } } try { httpclient.close(); } catch (IOException e) { } } return null; }
From source file:com.cisco.cta.taxii.adapter.httpclient.BasicAuthHttpRequestFactoryTest.java
@Before public void setUp() throws Exception { httpClient = HttpClients.createDefault(); credentialsProvider = Mockito.mock(CredentialsProvider.class); connSettings = TaxiiServiceSettingsFactory.createDefaults(); proxySettings = new ProxySettings(); credentialsProvider = Mockito.mock(CredentialsProvider.class); factory = new BasicAuthHttpRequestFactory(httpClient, connSettings, proxySettings, credentialsProvider); MockitoAnnotations.initMocks(this); when(mockAppender.getName()).thenReturn("MOCK"); Logger authCacheLogger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(RequestAuthCache.class.getCanonicalName()); authCacheLogger.setLevel(Level.DEBUG); authCacheLogger.addAppender(mockAppender); }
From source file:com.wso2.code.quality.matrices.RestApiCaller.java
/** * calling the relevant API and saving the output to a file * * @param URL url of the REST API to be called * @param accessToken either the WSO2 PMT access accessToken or giihub.com access accessToken * @param requireCommitHeader should be true for accessing the github commit search API and false otherwise * @param requireReviewHeader should be true for accessing the github review API or false otherwise *//*from www . j a v a 2 s . c om*/ public Object callApi(String URL, String accessToken, boolean requireCommitHeader, boolean requireReviewHeader) throws CodeQualityMatricesException { BufferedReader bufferedReader = null; CloseableHttpClient httpclient = null; CloseableHttpResponse httpResponse = null; Object returnedObject = null; try { httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(URL); if (accessToken != null) { httpGet.addHeader("Authorization", "Bearer " + accessToken); // passing the accessToken for the API call } //as the accept header is needed for the review API since it is still in preview mode if (requireReviewHeader) { httpGet.addHeader("Accept", "application/vnd.github.black-cat-preview+json"); } //as the accept header is needed for accessing commit search API which is still in preview mode if (requireCommitHeader) { httpGet.addHeader("Accept", "application/vnd.github.cloak-preview"); } httpResponse = httpclient.execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); // to get the response code switch (responseCode) { case 200: //success bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } // creating a JSON object from the response String JSONText = stringBuilder.toString(); Object json = new JSONTokener(JSONText).nextValue(); // gives an object http://stackoverflow.com/questions/14685777/how-to-check-if-response-from-server-is-jsonaobject-or-jsonarray if (json instanceof JSONObject) { JSONObject jsonObject = (JSONObject) json; returnedObject = jsonObject; } else if (json instanceof JSONArray) { JSONArray jsonArray = (JSONArray) json; returnedObject = jsonArray; } logger.info("JSON response is passed after calling the given REST API"); break; case 401: // to handle Response code 401: Unauthorized throw new CodeQualityMatricesException("Response code 401 : Git hub access token is invalid"); case 403: // to handle invalid credentials throw new CodeQualityMatricesException( "Response Code:403 Invalid Credentials, insert a correct token for PMT"); case 404: // to handle invalid patch throw new CodeQualityMatricesException("Response Code 404: Patch not found, enter a valid patch"); default: returnedObject = null; } } catch (ClientProtocolException e) { throw new CodeQualityMatricesException("ClientProtocolException when calling the REST API", e); } catch (IOException e) { throw new CodeQualityMatricesException("IOException occurred when calling the REST API", e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { throw new CodeQualityMatricesException("IOException occurred when closing the BufferedReader", e); } } if (httpResponse != null) { try { httpResponse.close(); } catch (IOException e) { throw new CodeQualityMatricesException("IOException occurred when closing the HttpResponse", e); } } if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { throw new CodeQualityMatricesException("IOException occurred when closing the HttpClient", e); } } } return returnedObject; }