JIRA API 集成经验总结

JIRA集成总结

由于工作需要, 系统需要集成JIRA API去自动创建ticket, 期间几乎没有遇到太多坑, 可能和JIRA API document规范有关吧, 不得不说,JIRA API document 是我见过的比较规范的文档之一.  通过阅读JIRA API Document, 我们可以发现 集成JIRA API需要OAUTH 或者Http Basic Authentication认证, 我这边是用的http Basic Authentication 方式, 下面是请求相关的参数配置

Attribute Name Description
Base URI The base jira uri. For example, https://yourjirahost.com
Header.Authorization This is a base64 format string. Its plaintext format is username:password. The value format in the header is Basic {base64}. For example, Basic MTIzNDU2Nzg=
Header.Accept application/json
Header.ContentType application/json

Main APIs

URL Method Description Request Parameter
/rest/api/2/issue POST Single Create issue 查看代码
{
    "fields": {
        "project": {
            "key": "MyProject"
        },
        "summary": "[Test] Please ignore this issue",
        "description": "[Test] Please ignore this issue. CC:[~san.zhang]",
        "issuetype": {
            "name": "Story"
        },
        "assignee": {
            "name": "san.zhang"
        },
        "customized_number":"这里是自定义参数"
    }
}
/rest/api/2/issue/issueId PUT Single Update issue { "fields": { "assignee":{"name":"charlie"} } }
rest/api/2/issue/myissueid/comment POST Add comment { "update" : { "components" : [{"add" : {"name" : "Engine"}}] } }
  POST Edit comment {
    "update": {
        "comment": [
            {
                "add": {
                    "body": "It is time to finish this task"
                }
            }
        ]
    }
}

下面是实现源代码

主要代码

//Add or edit
var fields = new MyClass()
{
    fields = new fields()
    {
        project = new project()
        {
            key = "myproject"
        },
        summary = "[Test] Please ignore this issue",
        description = "[Test] Please ignore this issue. CC:[~san.zhang]",
        assignee = new assignees() { name = "san.zhang" },
        issuetype = new issuetype()
        {
            name = "Story"
        },
        customfield_自定义号码 = "这是自定义字段"
    }
};
string JsonString = JsonConvert.SerializeObject(fields);
var requestMessage = new HttpRequestMessage
{
    RequestUri = new Uri(create_issue),
    Method = HttpMethod.Post, //Put for edit; Post for Create; Get for search
};
string encodeStr = $"{UserName}:{Password}";
var bytes = Encoding.UTF8.GetBytes(encodeStr);
string base64 = Convert.ToBase64String(bytes);
requestMessage.Headers.Add("Authorization", "Basic " + base64);
requestMessage.Headers.Add("Accept", "application/json");
requestMessage.Headers.Add("ContentType", "application/json");
requestMessage.Content = new StringContent(JsonString, Encoding.UTF8,
    "application/json");
try
{
    using (var cts = new CancellationTokenSource())
    {
        cts.CancelAfter(TimeSpan.FromMinutes(2));

        using (var responseA = await SendAsync(requestMessage, cts, 60000, false))
        {
            var res = await responseA.Content.ReadAsStringAsync(); //When updated successfully, response null here
        }
    }
}
catch (Exception ex)
{

}

 

http client公共方法

        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        /// <param name="cts">The CTS.</param>
        /// <param name="timeoutMilliseconds">The timeout seconds.</param>
        /// <param name="isUseDefaultCredentials">To identify whether apply to the default credential</param>
        /// <returns></returns>
        /// <exception cref="System.TimeoutException"></exception>
        public static async Task<HttpResponseMessage> SendAsync(HttpRequestMessage requestMessage, CancellationTokenSource cts, double timeoutMilliseconds = 60000, bool isUseDefaultCredentials = false)
        {
            try
            {
                if (isUseDefaultCredentials)
                {
                    using (HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
                    {
                        client.Timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                        return await client.SendAsync(requestMessage, cts.Token);
                    }
                }
                else
                {
                    using (HttpClient client = new HttpClient())
                    {
                        client.Timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                        return await client.SendAsync(requestMessage, cts.Token);
                    }
                }
            }
            catch (OperationCanceledException)
                when (!cts.IsCancellationRequested)
            {
                throw new TimeoutException();
            }
        }

 

posted @ 2022-11-29 17:05  竹林溪风  阅读(496)  评论(4编辑  收藏  举报