gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:02:41 25 4
gpt4 key购买 nike

问题

我正在尝试使用 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 block 时出现异常

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

访问 Jira Wiki here

最佳答案

#解决方案#

上面代码中的问题是 Jira 需要编码凭证。如果不对凭据进行编码,Jira 服务器将返回 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”,如果您执行字段、摘要、项目,它将不起作用它必须是字段、摘要、项目

关于c# - 创建问题 Jira REST API(400 错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54550748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com