restemplate发送安全认证的http请求

时间:2024-03-28 11:05:59

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

restemplate发送安全认证的http请求

发送请求时,需要把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<String> entity = new HttpEntity<>(header);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String sttr = response.getBody();