创建问题 Jira REST API(400 错误请求)

Create Issue Jira REST API (400 Bad Request)

问题

我正在尝试使用 HttpWebRequest 创建对我们内部 Jira 服务器的 REST API 调用。但不知何故,我不断收到 (400) Bad Request 错误。我也尝试过使用 WebClient 和其他方法,但我似乎没有找到正确的方法。有什么建议吗?

URL是正确的

用户正确

密码正确

JSON数据也正确

一定有其他方法可以访问远程服务器吧?我一直在寻找,但似乎没有找到解决方案。

我的代码

public static void CreateJiraRequest(JiraApiObject.RootObject jiraApiObject)
{
    string url = "https://jira-test.ch.*********.net/rest/api/latest/issue/";
    string user = "peno.ch";
    string password = "**********";

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Credentials = new System.Net.NetworkCredential(user, password);

    string data = JsonConvert.SerializeObject(jiraApiObject);

    using (var webStream = request.GetRequestStream())
    using (var requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
    {
        requestWriter.Write(data);
    }

    try
    {
        var webResponse = request.GetResponse();
        using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
        {
            string response = responseReader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

JSON

{
    "fields": {
       "project":
       {
          "key": "FOO"
       },
       "summary": "Test the REST API",
       "issuetype": {
          "name": "Task"
       }
   }
}

异常

request.GetResponse();

进入try块时出现异常

附加信息:远程服务器返回错误:(400) 错误请求。

访问 Jira Wiki here

#解决方案#

上面代码中的问题是 Jira 需要编码凭证。如果不对凭据进行编码,Jira 服务器将 return 没有特定信息的 400 Bad Request 错误。

我编写了两个新函数,一个用于 API 请求,一个用于凭证编码。

#API呼叫#

public static string PostJsonRequest(string endpoint, string userid, string password, string json)
    {
        // Create string to hold JSON response
        string jsonResponse = string.Empty;
        
        using (var client = new WebClient())
        {
            try
            {
                client.Encoding = System.Text.Encoding.UTF8;
                client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
                client.Headers.Add("Content-Type: application/json");
                client.Headers.Add("Accept", "application/json");
                var uri = new Uri(endpoint);
                var response = client.UploadString(uri, "POST", json);
                jsonResponse = response;
            }
            catch (WebException ex)
            {
                // Http Error
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
                    var statusCode = (int)wrsp.StatusCode;
                    var msg = wrsp.StatusDescription;
                    throw new HttpException(statusCode, msg);
                }
                else
                {
                    throw new HttpException(500, ex.Message);
                }
            }
        }

        return jsonResponse;
    }

#编码函数#

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

补充说明: Jira API 区分大小写,因此对于“POST”,如果您执行字段、摘要、项目,它将不起作用 它必须是字段、摘要、项目

我在 Jira 中创建一个 webhook 问题时遇到了一个非常相似的问题。问题是我无法说出为什么我从 Jira 收到“错误请求”,而请求看起来还不错。解决方案是在正确的级别启用日志记录。

为了调试请求,有必要去

System -> Logging and Profiling -> HTTP Access logging [Enable] and HTTP dump log [Enable].

此外

Configure logging level for another packages -> and insert org.apache.http with DEBUG level and if you are using a webhook also add com.atlassian.webhooks with DEBUG level.

然后安装“LASTLOG-ADD-ON”非常方便,然后在

中可用

Manage apps

并且您可以查看和搜索日志。错误消息在“atlassian-jira-http-dump.log”中显示了我的问题创建请求失败的原因。 希望这个设置对调试有帮助。