对Jenkins的纯Java REST API POST调用/reload或/restart始终返回禁止状态403,但可以工作 [英] Pure Java REST API POST calls to Jenkins /reload or /restart always return status 403 forbidden, but work
问题描述
运行此命令时出现异常,但是 Jenkins实际上执行了请求的操作:
I'm getting an Exception when running this, but Jenkins actually executes the requested action:
URL url = new URL("https://somehost.com/jenkins/quietDown");
HttpURLConnection c= (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(("user:apiToken").getBytes()));
c.getInputStream().close();
例外:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://somehost.com/jenkins/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at build.JenkinsClient.main(JenkinsClient.java:102)
使用Jenkins 2.164.3和Java 8进行测试.
Testing with Jenkins 2.164.3 and Java 8.
推荐答案
设置此设置可消除异常:
Setting this gets rid of the Exception:
connection.setInstanceFollowRedirects(false);
几个小时后,我注意到堆栈跟踪包含的URL与我发布到的URL略有不同:
After hours I noticed how the stack trace contained a slightly different URL than the one I was posting to:
https://somehost.com/jenkins/
vs
https://somehost.com/jenkins/quietDown
Jenkins似乎用重定向(302 Found
)回答,默认情况下,HttUrlConnections会从该重定向中读取该重定向(302 Found
),然后由于某种原因导致该异常.
It seems like Jenkins answers with a redirect (302 Found
), which the HttUrlConnections follows by default to read from, which then for some reason caused that exception.
在最长的时间内,我试图找到一种不调用connection.getInputStream()
即可发出POST请求的方法,但这似乎是唯一实际触发请求的调用.如果有人知道使用纯Java发出POST请求的另一种方法,请告诉我.
For the longest time, I tried to figure out a way to issue the POST request without calling connection.getInputStream()
, but that seems to be the only call which actually triggers the request. If anyone knows a different way to issue a POST request with pure Java, please let me know.
我知道我的URL和username:token
内容是正确的,因为我使用curl进行了测试(即使打开了Follow redirect选项,它也没有抱怨):
I knew my URL and username:token
stuff was correct because I tested with curl (which doesn't complain, even with the follow redirect option turned on):
curl -X POST https://somehost.com/jenkins/quietDown -u admin:token
curl -L -X POST https://somehost.com/jenkins/quietDown -u admin:token
这篇关于对Jenkins的纯Java REST API POST调用/reload或/restart始终返回禁止状态403,但可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!