import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Jenkins JOB 실행하는 프로그램
* - httpclient 4.3.x 이상 필요
* - 참고 : https://wiki.jenkins- ci.org/display/JENKINS/Authenticating+scripted+clients
*
* @author 엄승하
*/
public class TestCallJenkinsJob {
public String scrape(String urlString, String username, String password ) throws ClientProtocolException, IOException {
URI uri = URI.create( urlString);
HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri .getScheme());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(uri.getHost(), uri .getPort()), new UsernamePasswordCredentials(username , password));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(host , basicAuth);
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider( credsProvider).build();
HttpGet httpGet = new HttpGet(uri);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache );
HttpResponse response = httpClient .execute(host, httpGet, localContext );
return EntityUtils.toString(response.getEntity());
}
public static void main(String[] args) {
String jobUrl = "JOB URL(토큰정보 포함)" ;
String userNm = "계정ID" ;
String pwd = "계정 암호" ;
try {
String rslt = new TestCallJenkinsJob().scrape(jobUrl , userNm, pwd);
System. out.println("rslt: " + rslt);
} catch (IOException e ) {
e.printStackTrace();
}
}
}
'JAVA > Java 일반' 카테고리의 다른 글
openjdk 11설치 방법 및 기본 설정- java 11 설치 (0) | 2019.03.18 |
---|---|
apache http client의 타임아웃 관련(기본 값 등) - 버전마다 틀릴 수 있음 (0) | 2019.02.08 |
Java 변수 null처리에 따른 GC 테스트 샘플 (0) | 2018.06.18 |
JSP파일에서 JSTL의 html변경 후 남은 whitespace를 없애는 프로그램 Java 버전 (0) | 2017.07.12 |
STS(Eclipse) 기본 셋팅 (0) | 2016.06.18 |