【发布时间】:2020-01-15 13:59:40
【问题描述】:
好的,所以我对在代码中使用 API 非常陌生,而且我已经能够使用一些实际上非常简单的 API。但它们都不需要身份验证。我一直在尝试通过 C# 的 HttpClient 类使用 Jira 的 REST API 服务。见以下代码:
public void UpdateJiraIssue(string issueValue)
{
string url = $@"http://jira.mySite.com/rest/api/2/issue/{issueValue}/editmeta";
string jsonString = @"myNeatJsonData";
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
//Initialize Client
HttpClient apiClient = new HttpClient();
apiClient.BaseAddress = new System.Uri(url);
apiClient.DefaultRequestHeaders.Accept.Clear();
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
async Task RunJiraAPI()
{
using (HttpResponseMessage resp = await apiClient.PostAsync("editmeta", content))
{
if (resp.IsSuccessStatusCode)
{
var jsonSring = await resp.Content.ReadAsStringAsync();
}
}
}
RunJiraAPI();
return;
}
我遇到的问题是我收到 401 错误(身份验证)。这是我运行代码时我的“resp”对象包含的内容:
resp: {StatusCode: 401, ReasonPhrase: ' ', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-AREQUESTID: 400x1314x1
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Content-Security-Policy: frame-ancestors 'self'
X-ASEN: SEN-11158344
X-AUSERNAME: anonymous
Cache-Control: no-store, no-transform, no-cache
Set-Cookie: atlassian.xsrf.token=B2ZY-C2JQ-1AGH-PBLW_5ccc79da5af8e6abcb9bff5250f3305af3b2877a_lout; Path=/; Secure
WWW-Authenticate: OAuth realm="https%3A%2F%2Fjira.mySite.com"
X-Powered-By: ARR/3.0
X-Powered-By: ASP.NET
Date: Wed, 15 Jan 2020 13:40:22 GMT
Content-Length: 109
Content-Type: application/json; charset=UTF-8
}}
Request Message: {Method: POST, RequestUri: 'https://jira.rhlan.com/rest/api/2/issue/RHD-1116/editmeta', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Authorization: Basic cWE6aGVjc29mdDEyMw==
Accept: application/json
Content-Type: Application/json; charset=utf-8
Content-Length: 70
}}
Status Code: Unauthorized
我需要对我的 json 字符串进行一些处理以使其正常工作(这就是为什么我没有包含它实际包含的内容),但是一旦我通过了身份验证错误,我实际上可能会将其更改为通过 API 执行 get Jira 问题,这样我就可以看到以这种方式返回的所有 json 数据。然后我会相应地编辑我的 json 字符串。
有什么想法我在这里做错了吗?
【问题讨论】:
-
希望已清除响应消息中的任何个人数据,包括那个 base64 字符串。
-
查看文档here。你需要一个 api 令牌。
标签: c# api jira dotnet-httpclient