Spring 4.0.0 basic authentication with RestTemplate

前端 未结 6 1734
梦谈多话
梦谈多话 2020-12-13 10:37

I am currently working on integration of a third party application with our local reporting system. I would like to implement REST calls with basic authentication but facing

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 11:13

    I have another solution to set basic authentication for customized rest template.

    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
    headers = new ArrayList<>(); headers.add(header); // if we need proxy 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;

提交回复
热议问题