HttpClient简介
HTTP协议可能是现在Internet上使用得最多、最重要的协议了,越来越多的Java应用程序需要直接通过 HTTP协议来访问网络资源。虽然在JDK的java.net包中已经提供了访问HTTP协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
本文maven依赖版本如下:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
</dependency>
Jenkins上传插件
REQUEST
POST /pluginManager/uploadPlugin
HEADERS
Content-Type: multipart/form-data
BODY
File "filePath"
基于口令的安全认证登录jenkins:
HttpClient client = new HttpClient();
URL url = new URL(jenkinsHost);
int port = url.getPort() == -1 ? 80 : url.getPort();
Credentials credentials = new UsernamePasswordCredentials(userName, password);
AuthScope scope = new AuthScope(url.getHost(), port);
client.getState().setCredentials(scope, credentials);
client.getParams().setAuthenticationPreemptive(true);
通过PostMethod上传文件:
PostMethod postMethod = new PostMethod(jenkinsHost + "/pluginManager/uploadPlugin");
// Send any XML file as the body of the POST request
File f1 = new File("Z:\\workspace\\jenkins-plugin-hello.hpi");
FilePart filePart = new FilePart("file1", f1);// 用来上传文件的类
Part[] parts = { filePart };
MultipartRequestEntity entity = new MultipartRequestEntity(parts, new HttpMethodParams());
postMethod.setRequestEntity(entity);
int status = client.executeMethod(postMethod);
System.out.println(status);
System.out.println(postMethod.getResponseBodyAsString());
如果是普通的文本参数,可以使用StringPart类:
// Send any XML file as the body of the POST request
File f1 = new File("Z:\\workspace\\jenkins-plugin-hello.hpi");
FilePart filePart = new FilePart("file1", f1);// 用来上传文件的类
StringPart stringPart = new StringPart("name", "value");// 普通的文本参数
Part[] parts = { filePart, stringPart };
如果不是上传文件,而是简单的post文本信息,则
PostMethod postMethod = new PostMethod(url);
printStream.println("[INFO] URL(POST):" + url + " body:" + requestBody);
String responseBodyStr = "";
boolean flag = false;
//重试三次
for (int i = 0; i < 3; i++) {
if(flag){
break;
}
try {
postMethod.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "utf-8"));
postMethod.addRequestHeader(new Header("Content-Type", "application/json;charset=utf-8"));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setSoTimeout(120 * 1000);
client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
int status = client.executeMethod(postMethod);
String prefix = status == 200 ? "[INFO] 发布成功" : "【ERROR】 发布失败";
printStream.println(prefix + " statusCode:" + status);
String response = postMethod.getResponseBodyAsString();
if(isPrint) {
printStream.println(prefix + " response body:" + response);
}
if (status!=200) {
throw new Exception("status " + status);
}
responseBodyStr = response;
flag = true;
} catch (Exception e) {
if(i==2){
String msg = "【ERROR】 发布失败: " + e.getMessage() + ",第" + i + "次调用";
printStream.println(msg);
} else {
String msg = "发布失败: " + e.getMessage() + ",第" + i + "次调用";
printStream.println(msg);
}
e.printStackTrace(printStream);
} finally {
postMethod.releaseConnection();
}
}
查看Jenkins上nodes节点的slave机器情况
REQUEST
GET /computer/api/json
通过GetMethod获取信息:
GetMethod get = null;
try {
HttpClient client = getHttpClient(jenkinsHost);
StringBuffer consoleOutputUrl = new StringBuffer();
consoleOutputUrl.append(jenkinsHost).append("/computer/api/json");
get = new GetMethod(consoleOutputUrl.toString());
int result = client.executeMethod(get);
if(result == 200) {
String msg = get.getResponseBodyAsString();
return msg;
}
return "";
} catch (Exception e) {
LOG.error("获取出错:{}", e);
return "";
} finally {
if (get != null) {
get.releaseConnection();
}
}