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();

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章