簡體   English   中英

HttpClient 不返回 URI 的 json 值

[英]HttpClient not returning json value of URI

我正在嘗試使用 HttpClient 從 Jira 獲取信息,但我看不到任何信息。 我希望能夠獲得與某些過濾器匹配的所有錯誤,以便我可以將它們添加到我的程序中的表中。

我曾嘗試使用 rest api 訪問 Jira,但每次我這樣做時都說問題或項目不存在。 問題是,如果我在瀏覽器頂部的欄中輸入 URI,我可以看到我想要的 JSON 文本。 這讓我相信我的代碼沒有返回這些值的原因是因為授權問題。 我正在使用基本身份驗證來發送我的憑據。 我還想補充一點,我在 cmd 中使用了 cURL 來使用基本身份驗證測試我的憑據,並且它有效。

public async Task<JiraModel> GetBugs()
        {
           using (var client = new HttpClient())
            {
                string url = "https://myurl.atlassian.net/rest/api/3/project/VCMF";

                String username = "username";
                String password = "apikey";
                String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(username + ":" + password));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Basic " + encoded);
                client.BaseAddress = new Uri("https://myurl.atlassian.net/rest/api/3/project/VCMF");
                var response = await client.GetAsync(url);
                var content = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<JiraModel>(content);
            }
        }

在這段代碼的末尾,我應該得到 json 結果為字符串形式,但我一直收到 404 錯誤,而不是因為這段代碼明確表示“找不到帶有密鑰 'VCMF' 的項目”。

這里的問題是您錯誤地創建了授權 header。

您用於AuthenticationHeaderValue class 的構造函數需要兩個 arguments:方案和參數:

public AuthenticationHeaderValue(string scheme, string parameter)
{
}

第一個參數應該是方案(在本例中為基本),第二個參數應該是 base64 編碼的憑據:

所以而不是:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Basic " + encoded);

它應該是:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM