-
Bug
-
Resolution: Unresolved
-
Minor
-
None
-
Ubuntu 18.04LTS (amd64)
Jenkins 2.277.4
AdoptOpenJDK 11
I'm trying to write a shared library function that gets json from one of our servers. I'm able to open a connection, I get a 200 result but when I try to read the body I get an empty result.
If I try this same thing in the groovyConsole, or groovy command line, it works as I would expect.
Below is the groovy code I'm using; with an example call. I should note that the URL I'm using is not the URL data I'm trying to fetch but it's being used as an example URL.
protected String getJSON(String url, Map params = [:]) { int timeout = params['timeout'] ?: 300 HttpURLConnection c = null; try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod('GET'); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.setDoOutput(true) c.setDoInput(true) c.setRequestProperty('Content-Type', 'application/json; charset=UTF-8') c.connect(); int status = c.getResponseCode(); StringBuilder stringBuilder = new StringBuilder() BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(c.getInputStream())) String inputLine while ((inputLine = bufferedReader.readLine()) != null) { stringBuilder.append(inputLine) } bufferedReader.close() if (stringBuilder.length() > 0) { return stringBuilder.toString() } } catch (MalformedURLException ex) { LOGGER.severe(ex) } catch (IOException ex) { LOGGER.severe(ex) } finally { if (c != null) { try { c.disconnect(); } catch (Exception ex) { LOGGER.severe(ex) } } } return null; } getJSON("https://jenkins.<my local domain>.com/api/json")