I'm setting up some things and I need to access my Jenkins API. Well, everything works fine if I send a GET request to http://.../job/DogoBot/lastBuild/api/json
with restman and javascript's XMLHttpRequest, etc. But when I try HTTPURLConnector from java.net
it returns 403. I can't understand why, its the exact same GET request. I'm using that method made by my own with 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()
}
I'm testing with:
println(get("http://.../job/DogoBot/lastBuild/api/json"))
and I'm getting and Exception telling I got 403.