设置userName和密码时进行RestTemplate身份验证

时间:2017-08-02 07:37:08

标签: spring rest web-services spring-mvc

我有一个curl命令,但我想在调用其余API时使用userName和password传递此信息,我尝试过的每件事都不起作用。

curl -u E-BOARD:HVRid992Xl740NnWOkjk -X GET --header 'Accept: application/json' 'https://XXXXXX.fr/AAAAAA/BBBBB/v1/details?abc=hsdfh&zyx=asdfsdf

我的其他API看起来像这样

String url = new StringBuilder(urlConfigService.getProfiles().getBaseUrl()).append(relativeUrl).toString();
    **String hiddenAccess = "ASHGHGHJ:HVRid992Xl740NnWOkjk";**

    // @formatter:off
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("refEboard", refEboard)
            .queryParam("idLangue", "FR");
    // @formatter:on

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.add("Authorization", hiddenAccess);
    HttpEntity<?> httpEntity = new HttpEntity<String>(requestHeaders);
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    String result =
        restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, httpEntity, String.class).getBody();
    return (T) new Gson().fromJson(result, type.getClass());

1 个答案:

答案 0 :(得分:0)

在我看来,您正在尝试发送基本身份验证凭据。为此,您必须在Base64中编码用户名和密码,并设置如下所示的请求标头:

基本(用户名:密码Base64编码)

您就是这样做的:

{{1}}