Skip to content

Instantly share code, notes, and snippets.

@dileeph
Created January 7, 2016 00:42
Show Gist options
  • Save dileeph/74ab0d0ee80c9211059b to your computer and use it in GitHub Desktop.
Save dileeph/74ab0d0ee80c9211059b to your computer and use it in GitHub Desktop.
authenticated-rest-call
package com.dh.ts.repo;
import java.net.URI;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Repository
public class JenkinsRepository {
@Value("${jenkins.host}")
private String remoteAddress;
@Value("${jenkins.port}")
private String port;
@Value("${jenkins.username}")
private String username;
@Value("${jenkins.password}")
private String password;
private HttpHeaders createHeaders(final String username, final String password) {
return new HttpHeaders() {
private static final long serialVersionUID = 1L;
{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
}
};
}
public void invokeJob(String jobName) {
URI uri = UriComponentsBuilder.
newInstance().scheme("http").host(remoteAddress).port(port)
.pathSegment(new String[]{"/job/", jobName, "/build"}).build().toUri();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = createHeaders(username, password);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.exchange(uri, HttpMethod.POST, entity,
String.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment