SpringBoot使用Resttemplate进行Basic认证登录和Restful接口调用

直接贴代码

(推荐)方式一:使用RestTemplateBuilder自动配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;
    @Bean
    public RestTemplate restTemplate(){
        return restTemplateBuilder.basicAuthorization("admin","admin").build();
    }
}
@RestController
public class Test {

@Autowired
private RestTemplate restTemplate;

@RequestMapping(value = "/test")
private String getRestResponse() {
String url ="http://192.168.17.8:6080/service/public/v2/api/service/1";
try {
return restTemplate.getForObject(url, String.class);
} catch(Exception ex) {
return ex.toString();
}
}

方式二:复杂

import org.apache.commons.codec.binary.Base64;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class TestRanger {

    private static final String EXPECTED_MIME_TYPE = "application/json";
    static String rangerBaseUrl = "http://192.168.17.8:6080";
    
    public static void getPolicyByName() {
        
        String url = rangerBaseUrl + "/service/public/v2/api/service/1";
        String plainCreds = "admin:admin";
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        headers.add("Content-Type","application/json");
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String str = response.getBody();
        System.out.println(str);
    }
    
    public static void main(String[] args) {
        getPolicyByName();
    }
}
原文地址:https://www.cnblogs.com/erlou96/p/12167838.html