blob: c0bf70b8b38ce86abef3685999cca67550474eb1 [file] [log] [blame]
Sergey Kolekonovba203982016-12-21 18:32:17 +04001package com.mirantis.mk
2/**
3 *
4 * HTTP functions
5 *
6 */
7
8/**
9 * Make generic HTTP call and return parsed JSON
10 *
11 * @param url URL to make the request against
12 * @param method HTTP method to use (default GET)
13 * @param data JSON data to POST or PUT
14 * @param headers Map of additional request headers
15 */
16@NonCPS
17def sendHttpRequest(url, method = 'GET', data = null, headers = [:]) {
18
19 def connection = new URL(url).openConnection()
20 if (method != 'GET') {
21 connection.setRequestMethod(method)
22 }
23
24 if (data) {
25 headers['Content-Type'] = 'application/json'
26 }
27
28 headers['User-Agent'] = 'jenkins-groovy'
29 headers['Accept'] = 'application/json'
30
31 for (header in headers) {
32 connection.setRequestProperty(header.key, header.value)
33 }
34
35 if (data) {
36 connection.setDoOutput(true)
37 if (data instanceof String) {
38 dataStr = data
39 } else {
40 dataStr = new groovy.json.JsonBuilder(data).toString()
41 }
42 def output = new OutputStreamWriter(connection.outputStream)
43 //infoMsg("[HTTP] Request URL: ${url}, method: ${method}, headers: ${headers}, content: ${dataStr}")
44 output.write(dataStr)
45 output.close()
46 }
47
48 if ( connection.responseCode == 200 ) {
49 response = connection.inputStream.text
50 try {
51 response_content = new groovy.json.JsonSlurperClassic().parseText(response)
52 } catch (groovy.json.JsonException e) {
53 response_content = response
54 }
55 //successMsg("[HTTP] Response: code ${connection.responseCode}")
56 return response_content
57 } else {
58 //errorMsg("[HTTP] Response: code ${connection.responseCode}")
59 throw new Exception(connection.responseCode + ": " + connection.inputStream.text)
60 }
61
62}
63
64/**
65 * Make HTTP GET request
66 *
67 * @param url URL which will requested
68 * @param data JSON data to PUT
69 */
70def sendHttpGetRequest(url, data = null, headers = [:]) {
71 return sendHttpRequest(url, 'GET', data, headers)
72}
73
74/**
75 * Make HTTP POST request
76 *
77 * @param url URL which will requested
78 * @param data JSON data to PUT
79 */
80def sendHttpPostRequest(url, data = null, headers = [:]) {
81 return sendHttpRequest(url, 'POST', data, headers)
82}
83
84/**
85 * Make HTTP PUT request
86 *
87 * @param url URL which will requested
88 * @param data JSON data to PUT
89 */
90def sendHttpPutRequest(url, data = null, headers = [:]) {
91 return sendHttpRequest(url, 'PUT', data, headers)
92}
93
94/**
95 * Make HTTP DELETE request
96 *
97 * @param url URL which will requested
98 * @param data JSON data to PUT
99 */
100def sendHttpDeleteRequest(url, data = null, headers = [:]) {
101 return sendHttpRequest(url, 'DELETE', data, headers)
102}