gpt4 book ai didi

C# JIRA 工作日志更新错误 "The remote server returned an error: (401) Unauthorized."

转载 作者:太空宇宙 更新时间:2023-11-03 20:08:34 25 4
gpt4 key购买 nike

我将通过 C# 应用程序上的 JIRA REST API 更新 JIRA 中问题的工作日志。以下代码显示了我到目前为止所做的事情。

HttpWebResponse 返回此错误 “远程服务器返回错误:(401) 未经授权。”

我尝试使用相同的凭据并在 PHP cURL 函数中使用相同的数据,它工作正常并成功更新了问题工作日志。

这是我的 Jason 转换序列化对象:{"update":{"worklog":[{"add":{"comment":"IJ 的示例测试评论","timeSpent":"210"}}]}}

protected string RunQuery(JiraResource resource, string argument = null, string data = null, string method = "PUT")
{
// Where;
// resource = issue
// argument = "JIRA-16"
// Data = {"update":{"worklog":[{"add":{"comment":"Sample test comment by IJ","timeSpent":"210"}}]}}
// Method = "PUT"

string url = string.Format("{0}{1}/", m_BaseUrl, resource.ToString());

if (argument != null)
{
url = string.Format("{0}{1}", url, argument);
}

// URL = https://companyname.atlassian.net/rest/api/2/issue/JIRA-16

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
request.ContentLength = data.Length;

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}

string base64Credentials = GetEncodedCredentials(); // check below
request.Headers.Add("Authorization", "Basic " + base64Credentials);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;// here returns the error
//The remote server returned an error: (401) Unauthorized.

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}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}

我哪里做错了?请帮助我。

最佳答案

可能的原因:您在发送请求流之后添加了授权 header 。

   var request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
request.ContentLength = data.Length;

// All headers MUST be added before writing to request stream
request.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}

关于C# JIRA 工作日志更新错误 "The remote server returned an error: (401) Unauthorized.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21449861/

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