Search code examples
springresttemplateconfluence

connect with RestTemplate to Atlassian products (confluence)


I will connect to Atlassian application confluence with Spring RestTemplate and this works:

RestTemplate template = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Cookie",
        "_ga=GA1.2.62774864.1458801518; __utma=1.62774864.1458801518.1464093373.1464682866.13; __utmz=1.1458816981.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ga=GA1.3.62774864.1458801518; ki_t=1461064684094%3B1461064684094%3B1461069734488%3B1%3B2; ki_r=; seraph.confluence=5865502%3Adaa119bfd220fe01ddb5ebfb63fadf2c1f1e24ed; mywork.tab.tasks=false; JSESSIONID=AD61DF5C74564DBB35DB251EC3C8D6AD.it-confl02; crowd.token_key=0BJ0f0iIyp0TfFJnPo1PyA00");
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<String> response = template.exchange("https://confluence.domain.net/rest/api/content/search?cql=space=KIIOCO",
        HttpMethod.GET, requestEntity, String.class);
    System.out.println(response.getBody());

with cookie, but I will prevent using this long cookie string. Is there any possibility to replace this cookie?


Solution

  • Can't you send your Basic auth as a header instead of the cookie?

    I removed your cookie code, and instead sent the username and password each time, and it worked:

        package hello;
    
    
        import org.springframework.http.HttpEntity;
        import org.springframework.http.HttpHeaders;
        import org.springframework.http.HttpMethod;
        import org.springframework.web.client.RestTemplate;
    
        import java.io.IOException;
        import java.util.Base64;
    
    
        public class Application {
    
            public static void main(String args[]) throws IOException {
                RestTemplate template = new RestTemplate();
    
                HttpHeaders httpHeaders = getHeaders();
                HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);
                HttpEntity<String> response = template.exchange("https://confluence.domain.net/rest/api/content/search?cql=space=KIIOCO",
                        HttpMethod.GET, requestEntity, String.class);
                System.out.println(response.getBody());
            }
    
            public static HttpHeaders getHeaders() {
                String plainCreds = "my-username:my-password";
                byte[] base64CredsBytes = Base64.getEncoder().encode(plainCreds.getBytes());
                String base64Creds = new String(base64CredsBytes);
    
                HttpHeaders headers = new HttpHeaders();
                headers.add("Authorization", "Basic " + base64Creds);
    
                return headers;
            }
        }