Monday, October 21, 2024

Call API JIRA C# and Groovy (example)

Hello everyone, due to the current life circumstances, I have to master not just new technologies and platforms, so I am starting my journey by mastering new platforms for me, JIRA and Confluence, and accordingly I will also master the languages and frameworks JAVA, Groovy, Grails. In this post, I will give examples of calling the JIRA API using C# and Groovy, and then it will get even more interesting.
C# (example):
public static string GetEncodedCredentials(string UserName, string Password)
        {
            string mergedCredentials = String.Format("{0}:{1}", UserName, Password);
            byte[] byteCredentials = Encoding.UTF8.GetBytes(mergedCredentials);
            return Convert.ToBase64String(byteCredentials);
        }
        static void Main(string[] args)
        {
            string baseUrl = "http://jira.server.net:8080";
            string UserName = "login";
            string Password = "password";
            try
            {
                string restUrl = String.Format("{0}/rest/api/2/project", baseUrl);
                HttpWebResponse response = null;
                HttpWebRequest request = WebRequest.Create(restUrl) as HttpWebRequest;
                request.Method = "GET";
                request.Accept = "application/json";
                request.ContentType = "application/json";
                request.Headers.Add("Authorization", "Basic " + GetEncodedCredentials(UserName, Password));

                using (response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string responseContent = reader.ReadToEnd();
                    dynamic data = JsonConvert.DeserializeObject(responseContent);
                    var array = data;

                    for (int i = 0; i < array.Count; i++)
                    {
                        var resp = array[i];
                        string name = resp.name;
                        Console.WriteLine(name);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.ReadLine();
        }
Groovy (example):
import groovy.json.JsonSlurper 
def conn = "http://jira.server.net:8080/rest/api/2/project/".toURL().openConnection()
conn.setRequestProperty('Authorization', 'Basic ' + 'login:password'.bytes.encodeBase64().toString())
 if(conn.responseCode == 200) {
     def jsonSlurper = new JsonSlurper()
     def result = jsonSlurper.parseText(conn.content.text)
     println "json name:${result.name}"
 } else {
     println "Something bad happened."
     println "${conn.responseCode}: ${conn.responseMessage}"
 }

Happy Coding!

No comments:

Post a Comment