原文連接:https://www.jianshu.com/p/d6ab78e4ed73?tdsourcetag=s_pcqq_aiomsg
一、背景
我們目前正在對Jenkins進行二次開發,開源社區提供了針對jenkins的API,如:https://github.com/jenkinsci/java-client-api
但是,API支持的功能並不是很完善,如沒有發現支持用戶憑證的相關接口, 因此,只能通過其他解決方案來實現。
二、解決方案
2.1 curl命令行
參考文獻:
https://stackoverrun.com/cn/q/8142466
2.1.1 方式一
curl -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \ --data-urlencode 'json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }'
2.1.2 方式二
如果方式一,報403錯誤,如下所示:
<body><h2>HTTP ERROR 403</h2> <p>Problem accessing /credentials/store/system/domain/_/createCredentials. Reason: <pre> No valid crumb was included in the request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>
可以使用下面的方式
CRUMB=$(curl -s 'http://user:token@jenkins_server:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') curl -H $CRUMB -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \ --data-urlencode 'json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }'
2.2 Postman測試工具

postman測試post

查看原生的發送請求方式
如何看得懂,上面的協議呢?
https://blog.csdn.net/hairetz/article/details/6047905
2.3 Java代碼
- 依賴的jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.1</version> </dependency>
- 代碼如下:
public static void createUserCre(String id) { String url = "http://admin:11a8ff57440f35baead7a3cc8a21ec2c44@172.16.91.121:8888/jenkins/credentials/store/system/domain/_/createCredentials?"; HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; JSONObject jsonParam = new JSONObject(); JSONObject credentialsJsonParam = new JSONObject(); credentialsJsonParam.put("scope", "GLOBAL"); //注意,如果ID一樣的話,插入失敗 credentialsJsonParam.put("id", id); credentialsJsonParam.put("username", "abc520"); credentialsJsonParam.put("password", "123456"); credentialsJsonParam.put("description", "hello world jenkins hellow"); credentialsJsonParam.put("$class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"); jsonParam.put("credentials", credentialsJsonParam); jsonParam.put("", "0"); logger.info("=============:\t" + jsonParam.toString()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("json", jsonParam.toString(), ContentType.MULTIPART_FORM_DATA); HttpEntity multipart = builder.build(); HttpResponse resp = null; try { httpPost.setEntity(multipart); resp = client.execute(httpPost); //注意,返回的結果的狀態碼是302,非200 if (resp.getStatusLine().getStatusCode() == 302) { HttpEntity he = resp.getEntity(); logger.info("----------------123----------666666---"); respContent = EntityUtils.toString(he, "UTF-8"); } } catch (Exception e) { logger.error(e.getMessage()); } logger.info("=========================:\t" + respContent); logger.info("=========================:\t" + resp.getStatusLine().getStatusCode()); }
開發時,可以根據自己的實際情況,進行調整。
三、補充
3.1 Java HttpClient 發送multipart/form-data帶有Json文件的Post請求
說明:發送multipart/form-data帶有Json文件的Post請求,文件內容其實就是json字符串,這種請求之前都是通過postman發的,見postman截圖

postman form-data json文件1

postman form-data json文件2
依賴的jar包 : httpclient-4.5.3.jar,httpmime-4.3.jar
- 代碼:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpMultipartFormdataDemo1 { public static void main(String[] args) throws ClientProtocolException, IOException { // 文件sTestsetFile:solr_etl_agent35.json是存有JSON字符串的文件 String sTestsetFile=System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"solr_etl_agent35.json"; String sURL="http://172.16.101.46:14401/editorialincre"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(sURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); // 把文件加到HTTP的post請求中 File f = new File(sTestsetFile); builder.addBinaryBody( "file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName() ); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity(); String sResponse=EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("Post 返回結果"+sResponse); } }
3.2 java實現http post通訊 並進行urlencode,編碼方式utf-8
- 通訊實現
package com.token; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { /** * 日志對象 */ private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class); private HttpClientUtil(){ } public static String doPost(String url, Map<String, String> param) { // 創建Httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 創建Http Post請求 HttpPost httpPost = new HttpPost(url); // 創建參數列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity); } // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e