Hi,
I'm trying to post a simple REST API call (hard-coded issue creation) to a test instance via Script Runner. The call should actually happen in a Script Listener but for debugging I'm using the Script Console. Unfortunately I'm stuck with a HTTP 400 response althought the call is successful using Postman.
import groovy.json.StreamingJsonBuilder
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import java.text.SimpleDateFormat
import java.text.DateFormat
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.comments.CommentManager
def baseURL = "http://test2.mydomain:8080/rest/api/2/issue/";
def body_req = [
"""
{ "fields":
{
"project": {"key": "ABC"},
"issuetype": {"name": "Bug"},
"summary": "My Issue.",
"description": "Test"
}
}
"""
]
URL url = new URL(baseURL);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setRequestProperty( "Authorization", "Basic T****************************************************************4" );
connection.requestMethod = "POST";
connection.doOutput = true;
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.outputStream.withWriter("UTF-8") { new StreamingJsonBuilder(it, body_req) }
connection.connect();
println("url: " + url);
println("Content:" + connection.getContent())
println("ResponseCode:" + connection.getResponseCode())
println("getResponseMessage:" + connection.getResponseMessage())
Outcome:
java.io.IOException: Server returned HTTP response code: 400 for URL: http://test2.mydomain:8080/rest/api/2/issue/
at java_net_URLConnection$getContent.call(Unknown Source)
at Script337.run(Script337.groovy:36)
In Postman it works:
Jira Core 7.12.3
Script Runner 5.4.48
Thanks for your help!
Cheers, Tom
I found a solution
def baseurl = ComponentAccessor.getApplicationProperties().getString("jira.baseurl")
def authString = "llll:pppp".bytes.encodeBase64().toString()
def remote = new HTTPBuilder(baseurl+"/rest/configuration-manager/api/1.3/snapshots")
def issueJson = remote.request(Method.POST, ContentType.JSON) { req ->
headers."Authorization" = "Basic ${authString}"
body = [ name :" My Project Snapshot",
description : "project snapshot",
scope : "projectWithIssues",
projectKey : ["XXXX"],
filters : [],
agileBoards : [],
dashboards : []
]
response.success = { resp, json ->
log.warn("Successful = " + json.messages)
}
response.failure = { resp, json ->
log.warn("Failed = " + json.messages)
}
}
Thanks! It works for me. I've only refactored it for posting pages into Confluence through REST API.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hello @Tom104Tom ,
You might want to try this approach
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
def http = new HTTPBuilder('http://localhost:2990/jira/rest/api/2/issue')
def authString = "admin:admin".getBytes().encodeBase64().toString();
http.request(POST, ContentType.JSON) {
requestContentType = ContentType.JSON
request.addHeader("authorization: Basic ${authString}", "ContentType: application/json")
body = [ fields:
"{\"project\": {\"key\": \"MIS\"},\"issuetype\": {\"name\": \"Task\"}, \"summary\": \"My new task hello world\",\"description\": \"Test\"}"
]
response.success = { resp, JSON ->
log.warn("Successful = " + JSON)
}
response.failure = { resp, JSON ->
log.warn("Failed = " + JSON)
}
}
This worked for me. Try it out and tell me how it goes.
Cheers,
Ian
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
I am getting errors as requestContentType is undeclared if I am trying with above code
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hello i'm trying to use this webservice in scriptrunner : "http://localhost:8081/rest/configuration-manager/api/1.3/snapshots"
it works fine with my rest api browser with this body
{
"name" : "My Project Snapshot with 13",
"description" : "Interesting snapshot",
"scope" : "projectWithIssues",
"projectKey" : ["EBDODI"],
"filters" : [ ],
"agileBoards" : [ ],
"dashboards" : [ ],
"options" : {
"checkCustomFieldValues" : true,
"includeAttachmentFiles" : true
}
}
but in script runner i get this
2019-09-09 13:17:34,686 WARN [common.UserScriptEndpoint]: Script console script failed: groovyx.net.http.ResponseParseException: at groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:495) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:223) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165) at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515) at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:434) at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:383) at groovyx.net.http.HTTPBuilder$request.call(Unknown Source) at Script101.run(Script101.groovy:19) Caused by: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object The current character read is '<' with an int value of 60 Unable to determine the current character, it is not a string, number, array, or object line number 1 index number 0 <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Oops - an error has occurred</title><script type="text/javascript">contextPath = "";</script><link type='text/css' rel='stylesheet' href='/static-assets/metal-all.css' media='all'><script src='/static-assets/jquery-min.js'></script><script src='/static-assets/metal-all.js'></script><meta name="decorator" content="none" /></head><body class=" error-page error500"><script type="text/javascript">document.body.className += " js-enabled";</script><div id="page"><header id="header" role="banner"></header><!-- #header --><section id="content" role="main"><div class="aui-page-panel"><div class="aui-page-panel-inner"><section class="aui-page-panel-content lowerContent"><div id="error-state"><span class="error-type"></span><h1>Sorry, we had some technical problems during your last operation.</h1><h2 class="technical-details-header"><span>Request assistance</span></h2><div id="technical-details-content" class="technical-details js-hidden"><p>Copy the content below and send it to your Jira Administrator</p><div class="technical-details-content" contentEditable readonly><h2>Technical details</h2><p class="referral">Log's referral number: <strong id="log-referral-id">e8addb10-2555-48f1-96a5-236f0ef8954a</strong></p><div class="info-section" id="causePanel"><h2>Cause</h2><p>Referer URL: <b>Unknown</b></p><pre>java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 16</pre><blockquote id="stacktrace" style="overflow-x: auto;"><pre>java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 16 ^
this is my code :
def http = new HTTPBuilder('http://localhost:8081/rest/configuration-manager/api/1.3/snapshots')
def authString = "admin:admin".getBytes().encodeBase64().toString();
http.request(POST, ContentType.JSON) {
requestContentType = ContentType.JSON
request.addHeader("authorization: Basic ${authString}", "ContentType: application/json")
body = [
"{'name' : 'My Project Snapshot with Issues','description' : 'Interesting snapshot','scope' : 'projectWithIssues','projectKey' : 'EBDODI', 'filters' : [],'agileBoards' : [],'dashboards' : [],'options' : {'checkCustomFieldValues' : 'true','includeAttachmentFiles': 'true'}}"
]
response.success = { resp, JSON ->
log.warn("Successful = " + JSON)
}
response.failure = { resp, JSON ->
log.warn("Failed = " + JSON)
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
@Admin Jira I get the same result. I am calling Jira REST endpoint from Scriptrunner REST endpoint.
I do not use basic auth. My environment requires a bearer token, but sending the bearer token in the header still returns the same error.
Did you ever get past this issue?
In my case, I will have to use a Java API instead, unless someone found a solution after May 2022 that allows the REST API to be called directly.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hello @DH ,
Can you try this script:
def baseurl = ComponentAccessor.getApplicationProperties().getString("jira.baseurl")
def authString = "llll:pppp".bytes.encodeBase64().toString()
def remote = new HTTPBuilder(baseurl+"/rest/configuration-manager/ api/1.3/snapshots")
def issueJson = remote.request(Method.POST, ContentType.JSON) { req ->
headers."Authorization" = "Basic ${authString}"
body = [ name :" Mon instantané de projet",
description : "project snapshot",
scope : "projectWithIssues",
projectKey : ["XXXX"],
filtres : [],
agileBoards : [], tableaux de
bord : []
]
response.success = { resp, json ->
log.warn( "Réussi = " + json.messages)
}
response.failure = { resp, json ->
log.warn("Échec = " + json.messages)
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.