org.apache.http.impl.client.HttpClientBuilder Java Examples

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 8 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #2
Source File: PhotosLibraryUploadCallable.java    From java-photoslibrary with Apache License 2.0 6 votes vote down vote up
/** Gets the number of bytes the server has received. */
private long getReceivedByteCount(String uploadUrl) throws IOException {
  HttpPost httpPost = createAuthenticatedPostRequest(uploadUrl);
  httpPost.addHeader(UPLOAD_PROTOCOL_HEADER, UPLOAD_PROTOCOL_VALUE);
  httpPost.addHeader(UPLOAD_COMMAND_HEADER, UploadCommands.QUERY);

  CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
  HttpResponse response = httpClient.execute(httpPost);

  if (response.getFirstHeader(UPLOAD_GRANULARITY_HEADER) != null) {
    updateOptimalChunkSize(
        Integer.parseInt(response.getFirstHeader(UPLOAD_GRANULARITY_HEADER).getValue()));
  }

  switch (response.getFirstHeader(UPLOAD_STATUS_HEADER).getValue()) {
    case UploadStatuses.ACTIVE:
      return Long.parseLong(response.getFirstHeader(RECEIVED_BYTE_COUNT_HEADER).getValue());
    case UploadStatuses.FINAL:
      return request.getFileSize();
    default:
      throw new IllegalStateException(ExceptionStrings.INVALID_UPLOAD_STATUS);
  }
}
 
Example #3
Source File: ConfigServerApiImpl.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough

    // Have experienced hang in socket read, which may have been because of
    // system defaults, therefore set explicit timeouts.
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
            .disableAutomaticRetries()
            .setUserAgent("node-admin")
            .setConnectionManager(cm)
            .build();
}
 
Example #4
Source File: HttpComponentsClientHttpRequestFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void assertCustomConfig() throws Exception {
	HttpClient httpClient = HttpClientBuilder.create().build();
	HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(httpClient);
	hrf.setConnectTimeout(1234);
	hrf.setConnectionRequestTimeout(4321);
	hrf.setReadTimeout(4567);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsClientHttpRequest request = (HttpComponentsClientHttpRequest)
			hrf.createRequest(uri, HttpMethod.GET);

	Object config = request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull("Request config should be set", config);
	assertTrue("Wrong request config type" + config.getClass().getName(),
			RequestConfig.class.isInstance(config));
	RequestConfig requestConfig = (RequestConfig) config;
	assertEquals("Wrong custom connection timeout", 1234, requestConfig.getConnectTimeout());
	assertEquals("Wrong custom connection request timeout", 4321, requestConfig.getConnectionRequestTimeout());
	assertEquals("Wrong custom socket timeout", 4567, requestConfig.getSocketTimeout());
}
 
Example #5
Source File: FaviconServlet.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    // Create a pool of HTTP connections to use to get the favicons
    client = HttpClientBuilder.create()
        .setConnectionManager(new PoolingHttpClientConnectionManager())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .build();
    // Load the default favicon to use when no favicon was found of a remote host
    try {
       defaultBytes = Files.readAllBytes(Paths.get(JiveGlobals.getHomeDirectory(), "plugins/admin/webapp/images/server_16x16.gif"));
    }
    catch (final IOException e) {
        LOGGER.warn("Unable to retrieve default favicon", e);
    }
    // Initialize caches.
    missesCache = CacheFactory.createCache("Favicon Misses");
    hitsCache = CacheFactory.createCache("Favicon Hits");
}
 
Example #6
Source File: AWSInstanceInfo.java    From signalfx-java with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to get the value for the AWSUniqueId dimension used in SignalFx AWS integrations.
 *
 * @param timeoutInMs
 *            how long to wait in milliseconds for AWS to respond
 * @return null if the value was not obtained for any reason
 */
public static String get(int timeoutInMs) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .build();
    HttpGet request = new HttpGet(URL);

    try {
        HttpResponse response = client.execute(request);
        JsonNode object = MAPPER.readTree(response.getEntity().getContent());

        return object.get(INSTANCE_ID).asText() + "_" + object.get(REGION).asText() + "_"
                + object.get(ACCOUNT_ID).asText();

    } catch (Exception e) {
        log.trace("Exception trying to execute {}, Exception: {} ", request, e);
    }

    return null;
}
 
Example #7
Source File: HttpRequest.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes a HTTP GET request and returns the response string.
 * @param uri The URI containing the request URL and request parameters.
 * @return the HTTP response string after executing the GET request
 */
public static String executeGetRequest(URI uri) throws IOException {
    HttpUriRequest request = new HttpGet(uri);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();

    HttpResponse httpResponse = HttpClientBuilder.create()
                                                 .setDefaultRequestConfig(requestConfig)
                                                 .build()
                                                 .execute(request);
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity, "UTF-8");

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
    }
}
 
Example #8
Source File: HttpClientUtil.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * httpClient post 获取资源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
Example #9
Source File: StandardDirectorUtils.java    From chaos-lemur with Apache License 2.0 6 votes vote down vote up
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
        new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .useTLS()
        .build();

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create()
        .disableRedirectHandling()
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLSocketFactory(connectionFactory)
        .build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}
 
Example #10
Source File: RealmsAPI.java    From FishingBot with GNU General Public License v3.0 6 votes vote down vote up
public RealmsAPI(AuthData authData) {
    BasicCookieStore cookies = new BasicCookieStore();

    BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
    BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
    BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));

    sidCookie.setDomain(".pc.realms.minecraft.net");
    userCookie.setDomain(".pc.realms.minecraft.net");
    versionCookie.setDomain(".pc.realms.minecraft.net");

    sidCookie.setPath("/");
    userCookie.setPath("/");
    versionCookie.setPath("/");

    cookies.addCookie(sidCookie);
    cookies.addCookie(userCookie);
    cookies.addCookie(versionCookie);

    client = HttpClientBuilder.create()
            .setDefaultCookieStore(cookies)
            .build();
}
 
Example #11
Source File: AbstractImportTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
protected String download(String url) throws Exception {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    String content = null;
    InputStream stream = null;
    try {
        client = HttpClientBuilder.create().build();
        response = client.execute(new HttpGet(url));
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        stream = response.getEntity().getContent();
        content = IOUtils.toString(stream, "UTF-8");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }

    return content;
}
 
Example #12
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example #13
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void postLogoutWithExpiredIdToken() throws Exception {
    oauth.doLogin("test-user@localhost", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    oauth.clientSessionState("client-session");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String idTokenString = tokenResponse.getIdToken();

    // Logout should succeed with expired ID token, see KEYCLOAK-3399
    setTimeOffset(60 * 60 * 24);

    String logoutUrl = oauth.getLogoutUrl()
      .idTokenHint(idTokenString)
      .postLogoutRedirectUri(oauth.APP_AUTH_ROOT)
      .build();

    try (CloseableHttpClient c = HttpClientBuilder.create().disableRedirectHandling().build();
      CloseableHttpResponse response = c.execute(new HttpGet(logoutUrl))) {
        assertThat(response, Matchers.statusCodeIsHC(Status.FOUND));
        assertThat(response.getFirstHeader(HttpHeaders.LOCATION).getValue(), is(oauth.APP_AUTH_ROOT));
    }
}
 
Example #14
Source File: FlagsClient.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
    DelayedConnectionLevelRetryHandler retryHandler = DelayedConnectionLevelRetryHandler.Builder
            .withExponentialBackoff(Duration.ofSeconds(1), Duration.ofSeconds(20), 5)
            .build();
    return HttpClientBuilder.create()
            .setUserAgent("controller-flags-v1-client")
            .setSSLContext(identityProvider.getIdentitySslContext())
            .setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
            .setDefaultRequestConfig(RequestConfig.custom()
                                             .setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
                                             .build())
            .setMaxConnPerRoute(2)
            .setMaxConnTotal(100)
            .setRetryHandler(retryHandler)
            .build();
}
 
Example #15
Source File: HttpClientFactory.java    From riptide with MIT License 6 votes vote down vote up
private static HttpClientBuilder configureCaching(final Caching caching,
        @Nullable final Object cacheStorage) {
    final Heuristic heuristic = caching.getHeuristic();

    final CacheConfig.Builder config = CacheConfig.custom()
            .setSharedCache(caching.getShared())
            .setMaxObjectSize(caching.getMaxObjectSize())
            .setMaxCacheEntries(caching.getMaxCacheEntries());

    if (heuristic.getEnabled()) {
        config.setHeuristicCachingEnabled(true);
        config.setHeuristicCoefficient(heuristic.getCoefficient());
        config.setHeuristicDefaultLifetime(heuristic.getDefaultLifeTime().to(TimeUnit.SECONDS));
    }

    @Hack("return cast tricks classloader in case of missing httpclient-cache")
    CachingHttpClientBuilder builder = CachingHttpClients.custom()
                                                         .setCacheConfig(config.build())
                                                         .setHttpCacheStorage((HttpCacheStorage) cacheStorage)
                                                         .setCacheDir(Optional.ofNullable(caching.getDirectory())
                                                                              .map(Path::toFile)
                                                                              .orElse(null));
    return HttpClientBuilder.class.cast(builder);
}
 
Example #16
Source File: CommonUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static String doHttpPost(String uri, String token, String accessToken) throws Exception {

		HttpPost httpPost = new HttpPost(uri);
		httpPost.addHeader("content-type", "application/json");
		httpPost.addHeader("cache-control", "no-cache");
		if (!Strings.isNullOrEmpty(token)) {
			httpPost.addHeader("Authorization", token + " " + accessToken);
		}
		HttpClient httpClient = HttpClientBuilder.create().build();
		if (httpClient != null) {
			HttpResponse httpResponse;
			try {
				httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					return EntityUtils.toString(httpResponse.getEntity());
				} else {
					throw new Exception("unable to execute post request caused by"
							+ EntityUtils.toString(httpResponse.getEntity()));
				}
			} catch (Exception e) {
				logger.error("Error getting the data ", e);
				throw e;
			}
		}
		return "{}";
	}
 
Example #17
Source File: SonarHttpRequester.java    From sonar-quality-gates-plugin with MIT License 6 votes vote down vote up
private void loginApi(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance) {

        httpClientContext = HttpClientContext.create();
        httpClient = HttpClientBuilder.create().build();

        if (StringUtils.isNotEmpty(globalConfigDataForSonarInstance.getToken())) {
            token = globalConfigDataForSonarInstance.getToken();
        } else {
            HttpPost loginHttpPost = new HttpPost(globalConfigDataForSonarInstance.getSonarUrl() + getSonarApiLogin());

            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("login", globalConfigDataForSonarInstance.getUsername()));
            nvps.add(new BasicNameValuePair("password", globalConfigDataForSonarInstance.getPass()));
            nvps.add(new BasicNameValuePair("remember_me", "1"));
            loginHttpPost.setEntity(createEntity(nvps));
            loginHttpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            executePostRequest(httpClient, loginHttpPost);
        }

        logged = true;
    }
 
Example #18
Source File: AbstractPayPalNVPPaymentGatewayImpl.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
private String performPayPalApiCall(final String endpoint, final String callParams) throws IOException {

        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV call:\n{}", callParams.replace('&', '\n'));
        }

        final StringBuilder respBuilder = new StringBuilder();

        final HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setEntity(new StringEntity(callParams));

        final HttpClient client = HttpClientBuilder.create().build();

        final HttpResponse response = client.execute(httpPost);
        final BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));

        String _line;
        while (((_line = rd.readLine()) != null)) {
            respBuilder.append(_line);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV response:\n{}", respBuilder.toString().replace('&', '\n'));
        }
        return respBuilder.toString();
    }
 
Example #19
Source File: HttpClient.java    From jshERP with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 采用Post方式发送请求,获取响应数据
 *
 * @param url        url地址
 * @param param  参数值键值对的字符串
 * @return
 */
public static String httpPost(String url, String param) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(param);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        logger.info("状态:"+statusCode+"数据:"+data);
        return data;
    } catch(Exception e){
        throw new RuntimeException(e.getMessage());
    } finally {
        try{
            client.close();
        }catch(Exception ex){ }
    }
}
 
Example #20
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #21
Source File: ConduitAPIClient.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
/**
 * Call the conduit API of Phabricator
 *
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(IOUtils.toString(responseBody, Charset.defaultCharset()), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}
 
Example #22
Source File: ClusterDependentTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Helper (hacked together) method to grab a config from a bucket without having to initialize the
 * client first - this helps with pre-bootstrap decisions like credentials for RBAC.
 */
public static int[] minClusterVersion() throws Exception {
    int port = 8091;
    if (useMock) {
        port = mock().getHttpPort();
    }
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost(seedNode).setPort(port).setPath("/pools/default/buckets/" + bucket)
        .setParameter("bucket", bucket);
    HttpGet request = new HttpGet(builder.build());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(seedNode, port), new UsernamePasswordCredentials(adminUser, adminPassword));
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
    HttpResponse response = client.execute(request);
    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status > 300) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
    String rawConfig = EntityUtils.toString(response.getEntity());
    return minNodeVersionFromConfig(rawConfig);
}
 
Example #23
Source File: ApiClientTest.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
@Test(expected = ExecutorException.class)
public void executeGet() throws Exception {

    ApiClient devPortalExecutor = new ApiClient.DevPortalExecutorBuilder()
            .setEndpoint(EndPoint.PRODUCTION)
            .setSigningInformation("RS256", "kid", "")
            .setTokenRequesterId("token")
            .createDevPortalExecutor();

    setTestOverride(devPortalExecutor, true);
    Field field = devPortalExecutor.getClass().getDeclaredField("httpClient");
    field.setAccessible(true);
    field.set(devPortalExecutor, HttpClientBuilder.create().build());
    AuthProvider authProvider = Mockito.mock(HmacAuthProvider.class);
    assertNotNull(devPortalExecutor.execute(
            new StatusRequest.StatusRequestBuilder().createStatusRequest(), authProvider));
}
 
Example #24
Source File: HttpTransactionExecutor.java    From SmartApplianceEnabler with GNU General Public License v2.0 6 votes vote down vote up
public CloseableHttpResponse post(String url, ContentType contentType, String data, String username, String password) {
    logger.debug("{}: Sending POST request url={} contentType={} data={}", applianceId, url, contentType, data);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    withUsernameAndPassword(httpClientBuilder, username, password);
    CloseableHttpClient client = httpClientBuilder.setDefaultRequestConfig(getRequestConfig()).build();
    try {
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(data, contentType));
        CloseableHttpResponse response = client.execute(request);
        return logResponse(response);
    }
    catch(IOException e) {
        logger.error("{}: Error executing POST", applianceId, e);
        return null;
    }
}
 
Example #25
Source File: PoolingHttpClientFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient create(RequestConfig config, HttpRequestRetryHandler retryHandler, HttpClientConnectionManager connectionManager) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
    if (config != null)
        builder.setDefaultRequestConfig(config);
    if (retryHandler != null)
        builder.setRetryHandler(retryHandler);
    if (connectionManager != null)
        builder.setConnectionManager(connectionManager);
    return builder.build();
}
 
Example #26
Source File: AmazonAuthFilter.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param defaultFilterProcessesUrl the url of the filter
 */
public AmazonAuthFilter(final String defaultFilterProcessesUrl) {
	super(defaultFilterProcessesUrl);
	this.jreader = ParaObjectUtils.getJsonReader(Map.class);
	int timeout = 30 * 1000;
	this.httpclient = HttpClientBuilder.create().
			setConnectionReuseStrategy(new NoConnectionReuseStrategy()).
			setDefaultRequestConfig(RequestConfig.custom().
					setConnectTimeout(timeout).
					setConnectionRequestTimeout(timeout).
					setCookieSpec(CookieSpecs.STANDARD).
					setSocketTimeout(timeout).
					build()).
			build();
}
 
Example #27
Source File: JerseyApiLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenAddEmployee_whenJsonRequestSent_thenResponseCodeCreated() throws IOException {
    final HttpPost request = new HttpPost(SERVICE_URL);

    Employee emp = new Employee(5, "Johny");
    ObjectMapper mapper = new ObjectMapper();
    String empJson = mapper.writeValueAsString(emp);
    StringEntity input = new StringEntity(empJson);
    input.setContentType("application/json");
    request.setEntity(input);
    final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

    assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
}
 
Example #28
Source File: TelegramService.java    From torrssen2 with MIT License 5 votes vote down vote up
private void initialize() {
    token = settingService.getSettingValue("TELEGRAM_TOKEN");
    chatIds = StringUtils.split(settingService.getSettingValue("TELEGRAM_CHAT_ID"), ",");
    baseUrl = "https://api.telegram.org/bot" + token + "/sendMessage";
    
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
    httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();
}
 
Example #29
Source File: BasicAuthAnonReadTests.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void setAuth(SensorThingsService service, String username, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    URL url = service.getEndpoint();

    credsProvider.setCredentials(
            new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpClientBuilder clientBuilder = HttpClients.custom()
            .useSystemProperties()
            .setDefaultCredentialsProvider(credsProvider);

    CloseableHttpClient httpclient = clientBuilder.build();
    service.setClient(httpclient);
}
 
Example #30
Source File: HttpUtils.java    From instamojo-java with MIT License 5 votes vote down vote up
public static String post(String url, Map<String, String> customHeaders, String jsonPayload) throws IOException, HTTPException {
    LOGGER.log(Level.INFO, "Sending POST request to the url {0}", url);
    HttpPost httpPost = new HttpPost(url);

    if (customHeaders == null) {
        customHeaders = new HashMap<>();
    }

    customHeaders.put(Constants.HEADER_ACCEPT, "application/json");
    customHeaders.put(Constants.HEADER_CONTENT_TYPE, "application/json");

    populateHeaders(httpPost, customHeaders);

    if (jsonPayload != null || !jsonPayload.isEmpty()) {
        httpPost.setEntity(new StringEntity(jsonPayload));
    }

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse httpResponse = httpClient.execute(httpPost);

    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (isErrorStatus(statusCode)) {
        String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);
    }

    return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}