Search in sources :

Example 71 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project wildfly-swarm by wildfly-swarm.

the class SimpleHttp method getUrlContents.

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {
    StringBuilder content = new StringBuilder();
    int code;
    try {
        CredentialsProvider provider = new BasicCredentialsProvider();
        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!followRedirects) {
            builder.disableRedirectHandling();
        }
        if (useAuth) {
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }
        HttpClient client = builder.build();
        HttpResponse response = client.execute(new HttpGet(theUrl));
        code = response.getStatusLine().getStatusCode();
        if (null == response.getEntity()) {
            throw new RuntimeException("No response content present");
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new Response(code, content.toString());
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpResponse(org.apache.http.HttpResponse) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader)

Example 72 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project stdlib by petergeneric.

the class ResteasyClientFactoryImpl method createHttpClientCustomiser.

/**
 * N.B. This method signature may change in the future to add new parameters
 *
 * @param fastFail
 * @param authScope
 * @param credentials
 * @param preemptiveAuth
 * @param storeCookies
 * @param customiser
 *
 * @return
 */
public Consumer<HttpClientBuilder> createHttpClientCustomiser(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) {
    // Customise timeouts if fast fail mode is enabled
    if (fastFail) {
        customiser = concat(customiser, b -> {
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder.setConnectTimeout((int) fastFailConnectionTimeout.getMilliseconds()).setSocketTimeout((int) fastFailSocketTimeout.getMilliseconds());
            b.setDefaultRequestConfig(requestBuilder.build());
        });
    }
    // If credentials were supplied then we should set them up
    if (credentials != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (authScope != null)
            credentialsProvider.setCredentials(authScope, credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        // Set up bearer auth scheme provider if we're using bearer credentials
        if (credentials instanceof BearerCredentials) {
            customiser = concat(customiser, b -> {
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register("Bearer", new BearerAuthSchemeProvider()).build();
                b.setDefaultAuthSchemeRegistry(authSchemeRegistry);
            });
        }
        // Set up the credentials customisation
        customiser = concat(customiser, b -> b.setDefaultCredentialsProvider(credentialsProvider));
        if (preemptiveAuth && credentials instanceof BearerCredentials)
            customiser = concat(customiser, b -> b.addInterceptorFirst(new PreemptiveBearerAuthInterceptor()));
        else
            customiser = concat(customiser, b -> b.addInterceptorLast(new PreemptiveBasicAuthInterceptor()));
    }
    // If cookies are enabled then set up a cookie store
    if (storeCookies)
        customiser = concat(customiser, b -> b.setDefaultCookieStore(new BasicCookieStore()));
    return customiser;
}
Also used : AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) RegistryBuilder(org.apache.http.config.RegistryBuilder) Inject(com.google.inject.Inject) Timeout(com.peterphi.std.threading.Timeout) LogReportMessageBodyWriter(com.peterphi.std.guice.common.logging.logreport.jaxrs.LogReportMessageBodyWriter) RequestConfig(org.apache.http.client.config.RequestConfig) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) CommonTypesParamConverterProvider(com.peterphi.std.guice.restclient.converter.CommonTypesParamConverterProvider) ProxySelector(java.net.ProxySelector) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) ShutdownManager(com.peterphi.std.guice.common.shutdown.iface.ShutdownManager) Registry(org.apache.http.config.Registry) Credentials(org.apache.http.auth.Credentials) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) Doc(com.peterphi.std.annotation.Doc) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) StoppableService(com.peterphi.std.guice.common.shutdown.iface.StoppableService) AuthScope(org.apache.http.auth.AuthScope) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Named(com.google.inject.name.Named) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CredentialsProvider(org.apache.http.client.CredentialsProvider) Singleton(com.google.inject.Singleton) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) RegistryBuilder(org.apache.http.config.RegistryBuilder) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Registry(org.apache.http.config.Registry)

Example 73 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project sagacity-sqltoy by chenrenfei.

the class HttpClientUtils method doPost.

/**
 * @todo 执行post请求
 * @param sqltoyContext
 * @param nosqlConfig
 * @param url
 * @param jsonObject
 * @return
 * @throws Exception
 */
public static JSONObject doPost(SqlToyContext sqltoyContext, NoSqlConfigModel nosqlConfig, Object postValue) throws Exception {
    ElasticEndpoint esConfig = sqltoyContext.getElasticEndpoint(nosqlConfig.getUrl());
    if (esConfig.getUrl() == null)
        throw new Exception("请正确配置sqltoyContext elasticConfigs 指定es的服务地址!");
    String charset = (nosqlConfig.getCharset() == null) ? CHARSET : nosqlConfig.getCharset();
    HttpEntity httpEntity = new StringEntity(nosqlConfig.isSqlMode() ? postValue.toString() : JSON.toJSONString(postValue), charset);
    ((StringEntity) httpEntity).setContentEncoding(charset);
    ((StringEntity) httpEntity).setContentType(CONTENT_TYPE);
    String realUrl;
    // 返回结果
    HttpEntity reponseEntity = null;
    if (esConfig.getRestClient() != null) {
        realUrl = wrapUrl(esConfig.getPath(), nosqlConfig);
        if (sqltoyContext.isDebug())
            logger.debug("esRestClient执行:URL=[{}],Path={},执行的JSON=[{}]", esConfig.getUrl(), realUrl, JSON.toJSONString(postValue));
        // 默认采用post请求
        RestClient restClient = null;
        try {
            restClient = esConfig.getRestClient();
            Response response = restClient.performRequest("POST", realUrl, Collections.<String, String>emptyMap(), httpEntity);
            reponseEntity = response.getEntity();
        } catch (Exception e) {
            throw e;
        } finally {
            if (restClient != null)
                restClient.close();
        }
    } else {
        realUrl = wrapUrl(esConfig.getUrl(), nosqlConfig);
        HttpPost httpPost = new HttpPost(realUrl);
        if (sqltoyContext.isDebug())
            logger.debug("httpClient执行URL=[{}],执行的JSON=[{}]", realUrl, JSON.toJSONString(postValue));
        httpPost.setEntity(httpEntity);
        // 设置connection是否自动关闭
        httpPost.setHeader("Connection", "close");
        // 自定义超时
        if (nosqlConfig.getRequestTimeout() != 30000 || nosqlConfig.getConnectTimeout() != 10000 || nosqlConfig.getSocketTimeout() != 180000) {
            httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(nosqlConfig.getRequestTimeout()).setConnectTimeout(nosqlConfig.getConnectTimeout()).setSocketTimeout(nosqlConfig.getSocketTimeout()).build());
        } else
            httpPost.setConfig(requestConfig);
        CloseableHttpClient client = null;
        try {
            if (StringUtil.isNotBlank(esConfig.getUsername()) && StringUtil.isNotBlank(esConfig.getPassword())) {
                // 凭据提供器
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, // 认证用户名和密码
                new UsernamePasswordCredentials(esConfig.getUsername(), esConfig.getPassword()));
                client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
            } else
                client = HttpClients.createDefault();
            HttpResponse response = client.execute(httpPost);
            reponseEntity = response.getEntity();
        } catch (Exception e) {
            throw e;
        }
    }
    String result = null;
    if (reponseEntity != null) {
        result = EntityUtils.toString(reponseEntity, nosqlConfig.getCharset());
        if (sqltoyContext.isDebug())
            logger.debug("result={}", result);
    }
    if (StringUtil.isBlank(result))
        return null;
    // 将结果转换为JSON对象
    JSONObject json = JSON.parseObject(result);
    // 存在错误
    if (json.containsKey("error")) {
        String errorMessage = JSON.toJSONString(json.getJSONObject("error").getJSONArray("root_cause").get(0));
        logger.error("elastic查询失败,URL:[{}],错误信息:[{}]", nosqlConfig.getUrl(), errorMessage);
        throw new Exception("ElasticSearch查询失败,错误信息:" + errorMessage);
    }
    return json;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) RestClient(org.elasticsearch.client.RestClient) HttpResponse(org.apache.http.HttpResponse) ElasticEndpoint(org.sagacity.sqltoy.config.model.ElasticEndpoint) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Response(org.elasticsearch.client.Response) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity) JSONObject(com.alibaba.fastjson.JSONObject)

Example 74 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project carina by qaprosoft.

the class RestTemplateBuilder method build.

public RestTemplate build() {
    if (!isUseDefaultJsonMessageConverter) {
        HttpMessageConverter<?> httpMessageConverter = Iterables.tryFind(restTemplate.getMessageConverters(), new Predicate<HttpMessageConverter<?>>() {

            @Override
            public boolean apply(HttpMessageConverter<?> input) {
                return input instanceof MappingJackson2HttpMessageConverter;
            }
        }).orNull();
        restTemplate.getMessageConverters().remove(httpMessageConverter);
    }
    restTemplate.getMessageConverters().addAll(httpMessageConverters);
    if (isDisableSslChecking) {
        restTemplate.setRequestFactory(new DisabledSslClientHttpRequestFactory());
    }
    if (isUseBasicAuth) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuthUsername, basicAuthPassword));
        HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
    return restTemplate;
}
Also used : MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) AbstractHttpMessageConverter(org.springframework.http.converter.AbstractHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) DisabledSslClientHttpRequestFactory(com.qaprosoft.hockeyapp.http.resttemplate.ssl.DisabledSslClientHttpRequestFactory) Predicate(com.google.common.base.Predicate) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 75 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project service-proxy by membrane.

the class AssertUtils method getAuthenticatingHttpClient.

private static HttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }
            }
        }
    };
    HttpClient hc = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()).setDefaultCredentialsProvider(bcp).addInterceptorFirst(preemptiveAuth).build();
    return hc;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpContext(org.apache.http.protocol.HttpContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthState(org.apache.http.auth.AuthState) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)192 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)162 CredentialsProvider (org.apache.http.client.CredentialsProvider)147 AuthScope (org.apache.http.auth.AuthScope)104 HttpHost (org.apache.http.HttpHost)76 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)53 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)41 HttpResponse (org.apache.http.HttpResponse)38 IOException (java.io.IOException)35 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 HttpGet (org.apache.http.client.methods.HttpGet)30 HttpClient (org.apache.http.client.HttpClient)29 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)29 AuthCache (org.apache.http.client.AuthCache)28 BasicScheme (org.apache.http.impl.auth.BasicScheme)27 RequestConfig (org.apache.http.client.config.RequestConfig)25 HttpPost (org.apache.http.client.methods.HttpPost)20 Credentials (org.apache.http.auth.Credentials)19 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)19 Test (org.junit.Test)16