Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Celebration

Earn badges and make progress

You're on your way to the next level! Join the Kudos program to earn points and save your progress.

Deleted user Avatar
Deleted user

Level 1: Seed

25 / 150 points

Next: Root

Avatar

1 badge earned

Collect

Participate in fun challenges

Challenges come and go, but your rewards stay with you. Do more to earn more!

Challenges
Coins

Gift kudos to your peers

What goes around comes around! Share the love by gifting kudos to your peers.

Recognition
Ribbon

Rise up in the ranks

Keep earning points to reach the top of the leaderboard. It resets every quarter so you always have a chance!

Leaderboard

Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,640,537
Community Members
 
Community Events
196
Community Groups

Send post http request via scriptrunner post function

Deleted user Jun 18, 2017

Hello :)

 

Im wondering is there a way to send post http request via the scriptrunner postfunction feature?

 

The current script i have is JAVA:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n\"username\":\"USERNAME\",\r\n\"password\":\"PASSWORD\"\r\n}");
Request request = new Request.Builder()
  .url("http://IP ADDRESS/authentication")
  .post(body)
  .addHeader("content-type", "application/json")
  .addHeader("cache-control", "no-cache")
  .addHeader("postman-token", "dabd56ae-0efb-db67-72fe-657b5682a466")
  .build();

Response response = client.newCall(request).execute();

Anyone care to help to convert into groovyscript.

 

Many thanks!

Pon

 

 

4 answers

1 accepted

2 votes
Answer accepted
Daniel Yelamos [Adaptavist]
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 19, 2017

Hi Pon:

Doing a search on this I found a community question that might be helpful to you.

Here you will find a descriptive example on how to do this with Jira and Scriptrunner. If this isn't working for you, give me a thorough example on what you want to do and I will try to provide a custom script for you.

Cheers!

Dyelamos

 

Deleted user Jun 19, 2017

Hey Daniel, 

Thanks for the reply!

Im quite new to this, basically what im trying to do is call rest api to return a sucessful response which: 

 

i attempted the above, i dont see where i can place the auth/payload when sending the request, i tried searching also around and gotten around this far:

 

package com.hybris.activity

import groovyx.net.http.ContentType
import groovyx.net.http.RESTClient

 def activitiRestClient = new RESTClient("http://10.150.14.164:8090/authentication")
        activitiRestClient.auth.basic "USERNAME", "PASSWORD"

def response = activitiRestClient.get(
                   path: "/devices"
                )
println response.data.toString(2)

I have a python 3 code which is as follows (and works in python):

import http.client

conn = http.client.HTTPConnection("10.150.14.164:8090")

payload = "{\r\n\"username\":\"USERNAME\",\r\n\"password\":\"PASSWORD\"\r\n}"

headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "aace72a6-d5d2-1f44-23bf-4a10b6306b4c"
    }

conn.request("POST", "/authentication", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

which im trying to convert over to groovy script. 

Any guidance would be very helpful :)

 

Thanks, 

Pon

 

 

Daniel Yelamos [Adaptavist]
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 20, 2017

Hi Pon:

In this link you will find official documentation as to how to use httpBuilder to send a post request. That is the utility that we use to build post request in Adaptavist.

Cheers

DYelamos

 

Deleted user Jun 21, 2017

Thanks Daniel :) got it working. 

 

It was so simple all along:

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
import groovy.json.JsonSlurper
import net.sf.json.groovy.JsonSlurper

def http = new HTTPBuilder('http://IP/authentication')
http.request(POST) {
    requestContentType = ContentType.JSON
    body =  [username: 'USERNAME', password: 'PASSWORD']

        response.success = { resp, JSON ->

  return JSON
            
    }
    
        response.failure = { resp ->
        return "Request failed with status ${resp.status}"
            
            }
    }
Like Marko Slijepčević likes this
Daniel Yelamos [Adaptavist]
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 21, 2017

Glad you did mate! Thanks for the upvote and good luck in future programming! 

Cheers

 

Siavosh Kasravi
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Mar 03, 2019

Strange! This code gives me errors on multiple lines starting with 'requestContentType' and 'response' are not defined.

@Siavosh Kasravi 

Did you find out a way ? I am even facing errors with response as not defined

Siavosh Kasravi
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Apr 19, 2019
def url = 'https://www.aurl.net/somewhere/'
def post = new HttpPost(url)

post.addHeader("content-type", "application/json; charset=UTF-8")
post.setEntity(new StringEntity(jsonRequest, 'UTF-8'))


// execute

def client = HttpClientBuilder.create().build()
def response = client.execute(post)

def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def jsonResponse = bufferedReader.getText()

I used this. I think that groovy code is syntactically incorrect. You must use def for inferred  types.

@Daniel Yelamos [Adaptavist] I have the below code, which I want to run in groovy via scriptrunner

 

curl -x "proxyServer:port" -k "http url where I want to post the data" -d '{

"title" : "API Change",

"description": "Add loads of DNS records",

}'

 

Could you please help me so that I can write the same code in groovy.

 

Regards,

Sugandha

I'm pretty new to this and have only done one, but it's working so thought i'd share. I'm calling a Scriptrunner script from a Post Function to post to Monday.com. Hope this helps:

import groovy.json.JsonSlurper

<..cut out some variable defining...>

def msg1 = [
query : 'mutation{create_item (board_id: BOARDID,group_id:"GROUPNAME",item_name: "MYITEM"}") {id}}'
]

HttpResponse<String> jsonResp = post('https://api.monday.com/v2')
.header('Content-Type', 'application/json')
.header('Authorization', "${apiToken}")
.body(msg1)
.asString()

//now parse the results. 
def result = slurper.parseText(jsonResp.body)
Integer iid = result["data"]["create_item"]["id"] as Integer

//then I do another call using the "iid", pretty much same process as above but i don't need to parse the result.

@sburnett - possible to share the API token code? Our jira doesn't support Basic authentication anymore and I'm looking for a code that can pull token and use it for jira REST Endpoint authentication. 

0 votes
Kumar
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Apr 22, 2019 • edited

HI @Daniel Yelamos [Adaptavist]   I have a Similar requirement can you please help me With REST Call

I Need to Make a REST call Depends Upon the Value Selected in the Custom Field 

I have posted my requirement here Please go through this once please

https://community.atlassian.com/t5/Jira-questions/Is-that-Possible-to-make-a-REST-Call-from-Jira/qaq-p/1062294#M339355

Can you please me 

 

Thanks,

Kumar

@Daniel Yelamos [Adaptavist] 

Can you help me with the GET method to call a rest api and print the response

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events