无法调用REST Web服务。需要全面的身份验证

时间:2016-10-07 19:57:41

标签: spring rest

我目前正在开发spring应用程序和REST Web服务。 我在一个应用程序中创建了一个REST Web服务,并希望从其他应用程序访问该服务。 以下是尝试访问Web服务时显示的错误。

RestClientException : org.springframework.web.client.HttpClientErrorException: 401 Full authentication is required to access this resource

以下是我的网络服务代码:

@RequestMapping(value = MyRequestMapping.GET_ACC_DATA, method = RequestMethod.GET)
@ResponseBody
public MyResponseDTO getSigDataValues(@PathVariable final String acc, final HttpServletResponse response) throws Exception {
       MyResponseDTO  responseDTO = null;
       try {
             //logic goes here
             //responseDTO  = ..
        } catch (Exception e) {
             LOG.error("Exception" + e);
        }
        return responseDTO;
    }

我在另一个应用程序上面调用webservice。在下面提到的方法中,我正在调用webservice并向我抛出异常org.springframework.web.client.HttpClientErrorException

public MyResponseDTO getAccData(String acc){
       try{
           list= (List<String>)restTemplate.postForObject(MyDataURL.GET_ACC_DATA.value(), MyResponseDTO.class, acc);
        }
        catch (final RestClientException e)
        {
            LOG.info("RestClientException :" + e);
        }

请建议,我缺少什么。

2 个答案:

答案 0 :(得分:1)

您需要针对REST服务进行身份验证。最常见的方法之一是基本身份验证。如果这是服务使用的内容,则需要使用Base 64编码的usernamen + password创建AUTHORIZATION标头。

RestTemplate允许在发送请求之前设置客户标头。

答案 1 :(得分:0)

创建Authorization标头的过程对于基本身份验证来说相对简单,因此几乎可以通过几行代码手动完成:

private HttpHeaders createHeaders(String username, String password) {
    return new HttpHeaders() {
        private static final long serialVersionUID = -1704024310885506847L;
        {
            String auth = username + ":" + password;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
            String authHeader = "Basic " + new String(encodedAuth);
            set("Authorization", authHeader);
        }
    };
}

然后,发送请求变得非常简单:

ResponseEntity<Dados> response = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET,
            new HttpEntity<Dados>(createHeaders(usuario, senha)), Dados.class);