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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM