我正在设置一些东西,我需要访问我的Jenkins API。好吧,如果我使用restman和javascript的XMLHttpRequest等将GET请求发送到http://.../job/DogoBot/lastBuild/api/json
,一切都可以正常工作。但是,当我尝试从java.net
返回HTTPURLConnector时,它返回403。我不明白为什么,确切的说是相同的GET请求。我正在使用Kotlin自己制作的方法:
/**
* Sends a GET request to [url]. It can also be specified GET [args] and http [headers].
*
* @param[url] The URL to fetch
* @param[args] GET arguments (optional)
* @param[headers] HTTP Headers (optional)
*
* @return the body of the page.
* @throws java.io.IOException
*/
fun get(url: String, args: Array<Pair<String, String>> = emptyArray(), headers: Array<Pair<String, String>> = emptyArray()): String {
var url = url
if (args.isNotEmpty()) {
url += args.map {
Pair(URLEncoder.encode(it.first, "UTF-8"), URLEncoder.encode(it.second, "UTF-8"))
}.joinToString(separator = "&", prefix = "&")
}
val response = StringBuilder()
(URL(url).openConnection() as HttpURLConnection).let {
it.requestMethod = "GET"
headers.forEach { h ->
it.setRequestProperty(h.first, h.second)
}
it.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2")
it.inputStream.also {
BufferedReader(InputStreamReader(it)).also {
do {
val line = it.readLine()?.let { response.append("$it\n") }
} while (line != null)
}.close()
}.close()
}
return response.toString()
}
我正在测试:
println(get("http://.../job/DogoBot/lastBuild/api/json"))
我得到了,异常告诉我得到了403。