0

我正在设置一些东西,我需要访问我的 Jenkins API。http://.../job/DogoBot/lastBuild/api/json好吧,如果我使用 restman 和 javascript 的 XMLHttpRequest 等发送 GET 请求,一切正常。但是当我尝试 HTTPURLConnector 时,java.net它返回 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。

4

0 回答 0