• 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();
        }
    }
  • 相关阅读:
    Python的Crypto模块使用:自动输入Shell中的密码
    算法之动态规划初步(Java版)
    基于ZXing的二维码,你可以这样改造它
    Java字符编码的转化问题
    第一个Hadoop程序——WordCount
    Hadoop的学习前奏(二)——Hadoop集群的配置
    Linux下的一些问题收集及解决方法(二)
    Python的捕虫笔记
    Hadoop的学习前奏(一)——在Linux上安装与配置Hadoop
    Android SnackBar:你值得拥有的信息提示控件
  • 原文地址:https://www.cnblogs.com/erlou96/p/12167838.html
Copyright © 2020-2023  润新知