org.springframework.web.client.HttpClientErrorException:401未经授权

时间:2016-10-13 15:37:00

标签: spring spring-security spring-boot

我有网络服务网址:

http://myservice.local/aprovalanduser/?format=json&Name=India

当我使用

调用此URL时
resttemplate httpsrestTemplate.getForObject(uri, userdetails[].class)

我收到错误:

  

org.springframework.web.client.HttpClientErrorException:401 Unauthorized

在Web服务方法中:

method: "GET", 
data: xmlData, 
contentType: "application/xml", 
dataType: "xml", 
async: true, 
crossDomain: false,

我只为XML设置标题,如下所示:

headers.setContentType(MediaType.APPLICATION_XML);

2 个答案:

答案 0 :(得分:2)

Http状态代码401表示您需要提供凭据才能访问该服务。您提供凭据的方式取决于服务使用的身份验证机制

例如,如果它使用基本身份验证,那么您需要添加一个带有Basic前缀的Authorization请求标头和一个用户名和密码的base64编码组合,用以下内容分隔:

答案 1 :(得分:0)

这是@ekem chitsiga建议的执行基本身份验证的代码

String plainCreds = "username:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);

RestTemplate restTemplate = new RestTemplate();
String url = "http://myservice.local/aprovalanduser/?format=json&Name=India";
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, request, Object.class);
response.getBody();