简体   繁体   中英

HttpClient not returning json value of URI

I am trying to use HttpClient to GET information from Jira, but I am unable to see any of the information. I want to be able to get all the bugs that match certain filters so that I can add them to a table in my program.

I have tried to access Jira with the rest api, but every time I do it says that the issue or project doesn't exist. The thing is that if I enter the URI into the bar at the top of my browser I can see the JSON text that I want. This leads me to believe that the reason my code is not returning these values is because of an authorization issue. I am using basic auth to send my credentials. I also want to add that I used cURL in cmd to test my credentials with basic auth and it worked.

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);
            }
        }

I should be getting the json results in string form by the end of this length of code, but I keep getting a 404 error instead that for this code specifically says "No project could be found with key 'VCMF'".

The issue here is that you're creating the authorization header incorrectly.

The constructor you're using for AuthenticationHeaderValue class takes two arguments: scheme and parameter:

public AuthenticationHeaderValue(string scheme, string parameter)
{
}

The first argument should be the scheme (Basic in this case) and the second, the base64-encoded credentials:

So instead of:

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

It should be:

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM