我试图通过java在Jenkins中编辑我的工作,所以我做了一个URL连接和一个请求,但它没有用。我的代码如下:
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
public class JenkinsDesUpdate {
public static void main(String[] args) throws Exception {
URL url = new URL("https://$Login:$token@jenkinsURL/job/jobName/21/submitDescription");
Map <String,Object> params = new LinkedHashMap<>();
params.put("description", "NEW_DESCRIPTION_BLABLA");
StringBuilder postData = new StringBuilder();
for (Map.Entry <String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setRequestProperty ("Authorization", "Basic ");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(postDataBytes);
os.flush();
os.close();
int responseCode = conn.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
/*Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c); */
}
}
我得到的是: POST响应代码:: 200 window.location.replace(&#39; / JenkinsURL / login?from =%2FJenkinsURL%2Fjob%2FJobName%2F21%2FsubmitDescription&#39;); 需要验证
好像我无法进行身份验证,但我同时传递了登录信息和令牌(它使用密码而不是API令牌提供相同的结果)
答案 0 :(得分:1)
我认为问题是您没有传递任何内容来授权您的请求
conn.setRequestProperty ("Authorization", "Basic ");
您需要在此处附加您的授权密钥
例如:
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
试一试:)希望对您有所帮助!