RestTemplate 中设置 header 以及使用 HTTP 基本认证的方法

        String user = "111";
        String password = "66666";
        String userMsg = user + ":" + password;
        String base64UserMsg = Base64.getEncoder().encodeToString(userMsg.getBytes());
        System.out.println();
        System.out.println(base64UserMsg);

        String url = "http://url:port/arius/_sql";
        String postBody = "select count(*) from monitor";

        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent", "curl/7.58.0");
        headers.add("Authorization ", base64UserMsg);
        HttpEntity entity = new HttpEntity<>(postBody, headers);

        ResponseEntity response = restTemplate.postForEntity(url, entity, JSONObject.class);

        System.out.println(response.getBody().toJSONString());

参考资料:

1、How to set an “Accept:” header on Spring RestTemplate request?

https://stackoverflow.com/questions/19238715/how-to-set-an-accept-header-on-spring-resttemplate-request

2、HTTP Basic Authentication 基本认证
https://www.jianshu.com/p/258e20cc063c

3、HTTP 基本认证
https://www.ibm.com/support/knowledgecenter/zh/SSGMGV_3.2.0/com.ibm.cics.ts.internet.doc/topics/dfhtl2a.html


你可能感兴趣的:(Spring-基础)