List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public <T> T execute(final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException
From source file:it.govpay.web.console.utils.HttpClientUtils.java
public static HttpResponse getEsitoPagamento(String urlToInvoke, Logger log) throws Exception { HttpResponse responseGET = null;/*from w ww . j av a2 s .co m*/ try { log.debug("Richiesta Esito del pagamento in corso..."); URL urlObj = new URL(urlToInvoke); HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol()); CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpGet richiestaPost = new HttpGet(); richiestaPost.setURI(urlObj.toURI()); log.debug("Invio tramite client Http in corso..."); responseGET = client.execute(target, richiestaPost); if (responseGET == null) throw new NullPointerException("La Response HTTP e' null"); log.debug("Invio tramite client Http completato."); return responseGET; } catch (Exception e) { log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e); throw e; } }
From source file:me.ixfan.wechatkit.util.HttpClientUtil.java
/** * Send HTTP POST request with body of JSON data. * @param url URL of request.// w w w.j av a 2 s . c o m * @param jsonBody Body data in JSON. * @return JSON object of response. * @throws IOException If I/O error occurs. */ public static JsonObject sendPostRequestWithJsonBody(String url, String jsonBody) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpUriRequest request = RequestBuilder.post(url).setCharset(Charsets.UTF_8) .addHeader("Content-type", "application/json").setEntity(new StringEntity(jsonBody, Charsets.UTF_8)) .build(); return httpClient.execute(request, new JsonResponseHandler()); }
From source file:lucee.commons.net.http.httpclient4.HTTPEngineImpl.java
private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password, long timeout, boolean redirect, String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException { HttpClientBuilder builder = HttpClients.custom(); // redirect/* w w w . j ava 2 s. co m*/ if (redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); HttpHost hh = new HttpHost(url.getHost(), url.getPort()); setHeader(request, headers); if (CollectionUtil.isEmpty(formfields)) setContentType(request, charset); setFormFields(request, formfields, charset); setUserAgent(request, useragent); if (timeout > 0) builder.setConnectionTimeToLive(timeout, TimeUnit.MILLISECONDS); HttpContext context = setCredentials(builder, hh, username, password, false); setProxy(builder, request, proxy); CloseableHttpClient client = builder.build(); if (context == null) context = new BasicHttpContext(); return new HTTPResponse4Impl(url, context, request, client.execute(request, context)); }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password, long timeout, boolean redirect, String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException { HttpClientBuilder builder = getHttpClientBuilder(); // redirect//from w ww. java 2 s. c om if (redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); HttpHost hh = new HttpHost(url.getHost(), url.getPort()); setHeader(request, headers); if (CollectionUtil.isEmpty(formfields)) setContentType(request, charset); setFormFields(request, formfields, charset); setUserAgent(request, useragent); if (timeout > 0) Http.setTimeout(builder, TimeSpanImpl.fromMillis(timeout)); HttpContext context = setCredentials(builder, hh, username, password, false); setProxy(builder, request, proxy); CloseableHttpClient client = builder.build(); if (context == null) context = new BasicHttpContext(); return new HTTPResponse4Impl(url, context, request, client.execute(request, context)); }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java
private static CloseableHttpClient recordHttpClientForSingleJsonAndStatusCodeResponse(String jsonResponse, int statusCode) throws IOException { CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class); HttpEntity httpEntityMock = recordHttpEntityForContent(jsonResponse); when(httpResponseMock.getEntity()).thenReturn(httpEntityMock); StatusLine statusLineMock = recordStatusLine(statusCode); when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock); CloseableHttpClient httpClientMock = anyCloseableHttpClient(); when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock); return httpClientMock; }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java
private static CloseableHttpClient recordHttpClientForMultipleJsonAndStatusCodeResponse( List<String> jsonResponses, List<Integer> statusCodes) throws IOException { CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class); List<HttpEntity> httpEntities = jsonResponses.stream() .map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList()); when(httpResponseMock.getEntity()).thenReturn(httpEntities.get(0), httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1])); List<StatusLine> statusLines = statusCodes.stream().map(ConfluenceRestClientTest::recordStatusLine) .collect(toList());// w w w.j a v a 2 s. c o m when(httpResponseMock.getStatusLine()).thenReturn(statusLines.get(0), statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1])); CloseableHttpClient httpClientMock = anyCloseableHttpClient(); when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock); return httpClientMock; }
From source file:me.ixfan.wechatkit.util.HttpClientUtil.java
/** * Send HTTP request with specified HTTP method. * If method is not specified, GET method will be used. * @param url URL of request.//from w ww .j a va2s . co m * @param method HTTP method used. * @param nameValuePairs name/stringValue pairs parameter used as an element of HTTP messages. * @return JSON object of response. * @throws IOException If I/O error occurs. */ private static JsonObject sendRequestAndGetJsonResponse(String url, String method, NameValuePair... nameValuePairs) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpUriRequest request; switch (method) { case HttpPost.METHOD_NAME: request = RequestBuilder.post(url).setCharset(Charsets.UTF_8) .setEntity(new UrlEncodedFormEntity(Arrays.asList(nameValuePairs))).build(); break; default: request = RequestBuilder.get(url).setCharset(Charsets.UTF_8).build(); break; } return httpClient.execute(request, new JsonResponseHandler()); }
From source file:org.sead.repositories.reference.util.SEADAuthenticator.java
static public HttpClientContext authenticate(String server) { boolean authenticated = false; log.info("Authenticating"); String accessToken = SEADGoogleLogin.getAccessToken(); // Now login to server and create a session CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*ww w . j a v a 2 s . c o m*/ // //DoLogin is the auth endpoint when using the AUthFilter, versus // the api/authenticate endpoint when connecting to the ACR directly HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin"); List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1); nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken)); seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList)); CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // String seadSessionId = // EntityUtils.toString(resEntity); authenticated = true; } } else { // Seems to occur when google device id is not set on server // - with a Not Found response... log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Cannot read sead-google.json"); log.error(e.getMessage()); } // localContext should have the cookie with the SEAD session key, which // nominally is all that's needed. // FixMe: If there is no activity for more than 15 minutes, the session // may expire, in which case, // re-authentication using the refresh token to get a new google token // to allow SEAD login again may be required // also need to watch the 60 minutes google token timeout - project // spaces will invalidate the session at 60 minutes even if there is // activity authTime = System.currentTimeMillis(); if (authenticated) { return localContext; } return null; }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
private static long getLastModified(URL url) { CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try {// w ww . j av a 2s .c o m 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(); HttpHead request = new HttpHead(url.toURI()); request.setConfig(config); response = httpclient.execute(target, request); Header[] s = response.getHeaders("last-modified"); if (s != null && s.length > 0) { String lastModified = s[0].getValue(); return new Date(lastModified).getTime(); } } catch (Exception e) { logWarning(e); return -1; } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } try { httpclient.close(); } catch (IOException e) { } } return -1; }
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;//w ww . ja v a 2 s . c om 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; }