C#(.net) 调用jira 接口二次开发

请支持开源软件:https://gitee.com/bing300/aspfm

 

摘要

我们一直使用jira来收集管理用户需求及问题。为了方便用户提jira issue。我们自己开发的软件需要提供快速创建jira issue功能。

为此,研究jira提供的REST API实现了部分功能二次开发。根据实现原理,个人根据自己的需求,实现功能。

jira rest api地址:https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/

代码运行需要引用json序列化动态库:Newtonsoft.Json.dll

按照官网示例的JSON,根据对象,然后序列化,具体看实例.

官网要求:

C#(.net) 调用jira 接口二次开发_第1张图片

代码组装

C#(.net) 调用jira 接口二次开发_第2张图片

不废话,直接上传代码。

public class JiraApi
    {
        public string Username { get; private set; }
        public string Password { get; private set; }
        public string BaseURL { get; private set; }

        public JiraApi(string baseUrl,string username, string password)
        {
            BaseURL = baseUrl;
            Username = username;
            Password = password;
        }
        /// 
        /// 处理post请求,执行新建、编辑、删除等操作
        /// 
        /// json输入字符
        /// api的具体地址,一般是baseurl + 业务处理资源关键字
        /// Jira返回的WebResponse输出
        public string DoPost(string sData, string uri)
        {
            Uri address = new Uri(uri);
            HttpWebRequest request;
            //HttpWebResponse response1 = null;
            StreamReader sr;
            string returnXML = string.Empty;
            if (address == null) { throw new ArgumentNullException("address"); }
            try
            {
                request = WebRequest.Create(address) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/json";
                string base64Credentials = GetEncodedCredentials();
                request.Headers.Add("Authorization", "Basic " + base64Credentials);
                //request.Credentials = new NetworkCredential(sUsername, sPassword);
                if (sData != null)
                {
                    byte[] byteData = UTF8Encoding.UTF8.GetBytes(sData);
                    request.ContentLength = byteData.Length;
                    using (Stream postStream = request.GetRequestStream())
                    {
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                    using (HttpWebResponse response1 = request.GetResponse() as HttpWebResponse)
                    {
                        StreamReader reader = new StreamReader(response1.GetResponseStream());
                        string str = reader.ReadToEnd();
                        return str;
                    }
                }
                return "error";
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        try
                        {
                            string sError = string.Format("The server returned '{0}' with the status code {1} ({2:d}).",
                            errorResponse.StatusDescription, errorResponse.StatusCode,
                            errorResponse.StatusCode);
                            sr = new StreamReader(errorResponse.GetResponseStream(), Encoding.UTF8);
                            returnXML = sr.ReadToEnd();
                            return returnXML;
                        }
                        finally
                        {
                            if (errorResponse != null) errorResponse.Close();
                        }
                    }
                }
                else
                {
                    //throw new Exception(wex.Message);
                    return wex.Message;
                }
            }
        }

        /// 
        /// 处理get请求,执行查询操作
        /// 
        /// 输入的业务处理资源关键字,必填项
        /// 参数,用于获取具体查询操作,非必填项
        /// 暂时没用处,非必填项
        /// 默认为GET,非必填项
        /// 
        public string DoQuery(
        string resource,
        string argument = null,
        string data = null,
        string method = "GET")
        {
            string url = string.Format("{0}{1}/", BaseURL, resource.ToString());
            if (argument != null)
            {
                url = string.Format("{0}{1}/", url, argument);
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = method;
            if (data != null)
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(data);
                }
            }
            string base64Credentials = GetEncodedCredentials();
            request.Headers.Add("Authorization", "Basic " + base64Credentials);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string result = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }
            return result;

        }
        private string GetEncodedCredentials()
        {
            string mergedCredentials = string.Format("{0}:{1}", Username, Password);
            byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
            return Convert.ToBase64String(byteCredentials);
        }
    }

功能实现调用

class Program
    {
        static void Main(string[] args)
        {
           JiraApi manager = new JiraApi("http://localhost:8056/rest/api/2/", "aaaa","密码");

            //查询jira所有项目
            string jsonProjects = manager.DoQuery("project");

            //创建Issue
            var createmeta = new
            {
                fields = new
                {
                    project = new { key = "OCMESREQ" },//项目关键字(KEY)
                    summary = "33333",
                    description = "456",
                    issuetype = new { name = "任务" }
                }
            };
            string jsonData = JsonConvert.SerializeObject(createmeta);
            string jsonNewIssue = CreateIssue(manager, jsonData);
            dynamic newIssueObj = JsonConvert.DeserializeObject(jsonNewIssue);

            //对问题添加备注
            string str1 = SubmitComment(manager, newIssueObj.key.ToString(), "123");

            Console.ReadLine();
        }
        
        /// 
        /// 添加问题的备注
        /// 
        /// JiraApi实例
        /// 问题的关键字,比如SomeIssue-18
        /// 备注的内容
        private static string SubmitComment(JiraApi api, string issue, string comment)
        {
            string sData = "{\"body\": \""+ comment + "\"}";
            string uri = api.BaseURL + string.Format("issue/{0}/comment", issue);
            return api.DoPost(sData, uri);
        }


        private static string CreateIssue(JiraApi api,string sData)
        {
            string uri = api.BaseURL + string.Format("issue");
            return api.DoPost(sData, uri);
        }
    }

 

你可能感兴趣的:(Jira)