Sending GET request with Authentication headers using restTemplate

前端 未结 6 1363
执念已碎
执念已碎 2021-01-31 01:20

I need to retrieve a resources from my server by sending a GET request with the some Authorization headers using RestTemplate.

After going over the docs I noticed that

6条回答
  •  粉色の甜心
    2021-01-31 01:52

    Here's a super-simple example with basic authentication, headers, and exception handling...

    private HttpHeaders createHttpHeaders(String user, String password)
    {
        String notEncoded = user + ":" + password;
        String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", encodedAuth);
        return headers;
    }
    
    private void doYourThing() 
    {
        String theUrl = "http://blah.blah.com:8080/rest/api/blah";
        RestTemplate restTemplate = new RestTemplate();
        try {
            HttpHeaders headers = createHttpHeaders("fred","1234");
            HttpEntity entity = new HttpEntity("parameters", headers);
            ResponseEntity response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
            System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
        }
        catch (Exception eek) {
            System.out.println("** Exception: "+ eek.getMessage());
        }
    }
    

提交回复
热议问题