【问题标题】:Add proxy information and basic auth to the resttemplate using httpClient使用 httpClient 将代理信息和基本身份验证添加到 resttemplate
【发布时间】:2016-07-03 13:19:21
【问题描述】:

我的开发环境在代理后面,所以我需要将代理信息设置为其余模板,当我使用 HttpComponentsClientHttpRequestFactory 并在 httpClient 中设置代理设置并在模板中设置时,这一切都很好。

但现在我有一个需要基本身份验证的休息服务。并且要设置基本的身份验证凭据,我需要在其余模板上的 httpClient 中设置它们。但是我看到 httpClient 中的 getparams 方法已被废弃,所以我不能只更新模板中的现有客户端,如果我创建一个新的 httpclient 对象,我将覆盖在应用程序引导期间设置的代理信息。

那么有什么方法可以从其余模板中提取 httpClient 并更新它吗?或者有没有其他方法可以解决这个问题?

谢谢。

【问题讨论】:

    标签: spring proxy basic-authentication resttemplate


    【解决方案1】:

    配置httpClient如下:

    HttpHost target = new HttpHost("hostname", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    
    HttpHost proxy = new HttpHost("proxy", 12345);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setProxy(proxy)
            .setDefaultCredentialsProvider(credsProvider).build();
    
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpclient);
    
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    

    另见HttpClient Examples

    【讨论】:

    • 感谢@fateddy,我终于将它与 spring "@profile" 配置结合起来为开发和非开发环境创建了必要的其余模板。
    【解决方案2】:

    上面的解决方案对我不起作用,我解决了上面的问题,最后通过小修改使其工作。

    RestTemplate restTemplate = new RestTemplate();
        HttpHost proxy =null;
        RequestConfig config=null;
        String credentials = this.env.getProperty("uname") + ":" + this.env.getProperty("pwd");
        String encodedAuthorization = Base64.getEncoder().encodeToString(credentials.getBytes());
    
        Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuthorization);
        List<Header> headers = new ArrayList<>();
        headers.add(header);
    
        if(Boolean.valueOf(env.getProperty("proxyFlag"))){
            proxy = new HttpHost(this.env.getProperty("proxyHost"), Integer.parseInt(env.getProperty("proxyPort")), "http");
            config= RequestConfig.custom().setProxy(proxy).build();
        }else{
            config= RequestConfig.custom().build();
        }
    
    
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config)
                .setDefaultHeaders(headers).build();
    
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        restTemplate.setRequestFactory(factory);
    
        return restTemplate;
    

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2016-08-24
      • 2016-12-19
      • 2023-04-08
      • 2012-03-11
      • 2014-03-26
      相关资源
      最近更新 更多