program tip

httpClient.GetAsync를 사용할 때 헤더 추가

radiobox 2020. 8. 6. 08:12
반응형

httpClient.GetAsync를 사용할 때 헤더 추가


Windows 스토어 앱 프로젝트에서 Apiary.io로 다른 동료가 만든 API를 구현하고 있습니다.

그들은 내가 구현 해야하는 방법 의이 예를 보여줍니다.

var baseAddress = new Uri("https://private-a8014-xxxxxx.apiary-mock.com/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("user/list{?organizationId}"))
  {


    string responseData = await response.Content.ReadAsStringAsync();

 }
}

이 방법과 다른 방법에서는 이전에 얻은 토큰이있는 헤더가 필요합니다.

여기에 헤더임이있는 우편 배달부 (chrome extension) 이미지가 있습니다. 여기에 이미지 설명을 입력하십시오

승인 헤더를 요청에 어떻게 추가합니까?


HttpClient와 함께 GetAsync를 사용할 때 다음과 같이 인증 헤더를 추가 할 수 있습니다.

httpClient.DefaultRequestHeaders.Authorization 
                         = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

이것은 HttpClient의 수명 동안 인증 헤더를 추가하므로 인증 헤더가 변경되지 않는 한 사이트를 방문하는 경우 유용합니다.

자세한 답변 은 다음과 같습니다.


나중에 대답하지만 아무도이 솔루션을 제공하지 않았기 때문에 ...

If you do not want to set the header on the HttpClient instance by adding it to the DefaultRequestHeaders, you could set headers per request.

But you will be obliged to use the SendAsync() method.

This is the right solution if you want to reuse the HttpClient -- which is a good practice for

Use it like this:

using (var requestMessage =
            new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", your_token);
    httpClient.SendAsync(requestMessage);
}

The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:

client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

이것은 POST 요청을 참조하는 것이 아니라 GET 요청에도 사용할 수 있습니다.


greenhoorn의 답변에 따라 다음과 같이 "Extensions"를 사용할 수 있습니다.

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

그리고 사용하십시오 :

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")

참고 URL : https://stackoverflow.com/questions/29801195/adding-headers-when-using-httpclient-getasync

반응형