Forum Xamarin.iOS

HttpClient : how to send OAuth token inside GET request

amolasamolas Member ✭✭

We are testing usage of HttpClient for network communication in iOS app (Xamarin.iOS).
We are trying a GET request. The response that we get is "Missing access token".

Access token type is Bearer.We are using OAuth2.
We are using latest iOS SDK i.e., 12.1

We tried following 2 ways, none of them worked.

  1.     HttpClient httpClient = new HttpClient();
    
         var uri = new Uri("complete url");
    
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", String.Format("Basic {0}", AccessToken));
        var response = await httpClient.GetAsync(uri);
    
  2.     HttpClient httpClient = new HttpClient();
    
        var uri = new Uri("complete url");
        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
        requestMessage.Headers.TryAddWithoutValidation("Content-Type", "application/json");
        requestMessage.Headers.TryAddWithoutValidation("accessToken", AccessToken);
        requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
       var response = await httpClient.SendAsync(requestMessage);
    

We tried various options at this line httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", String.Format("Basic {0}", AccessToken)); . But none of them worked and everytime we are getting access token missing error.

In what way an access token is to be sent? Can anyone send us sample app for using HttpClient in iOS application?

Answers

  • amolasamolas Member ✭✭

    We could do it in simple way for GET request:
    HttpClient httpClient = new HttpClient();

             var uri = new Uri("https://Completeurl?accessToken="+ AccessToken);
    
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            var response = await httpClient.GetAsync(uri);
    

    This gave us proper results.

    Thanks All.

  • The below works for me, the syntax for the token is different that what you have.

    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.BearerToken);

    var response = await client.PostAsync("api/roles/getmyroles", null);

Sign In or Register to comment.