restemplate发送安全认证的http请求

业务中,会访问到需要安全认证的服务。如

restemplate发送安全认证的http请求_第1张图片

发送请求时,需要把resttemplate设置头信息,具体实现如下

        String url = "http://localhost:8080/testController";
        HttpHeaders header = new HttpHeaders();
        //输入自己的用户名和密码
        String userAndPass = "username:passworld";
        //Basic后有空格
        //Base64需要maven引入commons-codec
        header.add("Authorization", "Basic "+Base64.encodeBase64String(userAndPass.getBytes()));
        HttpEntity entity = new HttpEntity<>(header);
        ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String sttr = response.getBody();

 

 

你可能感兴趣的:(spring,restemplate)