Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

HttpGet with authorization header

sylmosssylmoss BRMember ✭✭

I need to retrieve some json data from web service, specifically FCM, but I can't find how to do that with and authorization header.

I was trying to use the following code:

            var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method = "GET";

but I can't put the necessary authorization header. I don't find nothing specific and clear of how to do this.

Need help

Answers

  • amolbadheamolbadhe USMember ✭✭

    The HttpClient class can set the Authorization header value on the HttpClient.DefaultRequestHeaders.Authorization property. Hope Below code will help you.

        public HttpClientHandler Handler { get; set; } = new NativeMessageHandler();
    
        public async void GetAsyncRequestCall()
        {
            var httpClient = new HttpClient(Handler);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("APP_VERSION", "1.0.0");
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_authorization_token_string");
            HttpResponseMessage response = await httpClient.GetAsync("https://example.com/xyz");
            var result = response.Content.ReadAsStringAsync().Result;;
    
        }
    
  • sylmosssylmoss BRMember ✭✭

    @amolbadhe it didn't work here :(

    I need to do the equivalent of this java code:

    HttpGet httpGet = new HttpGet("https://iid.googleapis.com/iid/info/" + userToken + "?details=true");
    
            // Header setzen
            httpGet.setHeader("Content-Type", "application/json");
            httpGet.setHeader("Authorization", "key=" + FCM_SERVER_KEY);
    
            HttpClient httpClient = HttpClientBuilder.create().build();
    
            BasicResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpClient.execute(httpGet, responseHandler);
    

    Any idea? Now I'm trying this one, and I get the authorization error as response

    using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", serverKey);
    
                using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                        {
                            string readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            DependencyService.Get<IFCMTopics>().setInformation(readHttpResponse);
                        }
                    }
                }
    
  • sylmosssylmoss BRMember ✭✭
    edited January 2017

    @amolbadhe I couldn't get your example working in my solution :/

    I need to do the equivalent of the following code

    HttpGet httpGet = new HttpGet("https://iid.googleapis.com/iid/info/" + userToken + "?details=true");
    
            // Header setzen
            httpGet.setHeader("Content-Type", "application/json");
            httpGet.setHeader("Authorization", "key=" + FCM_SERVER_KEY);
    
            HttpClient httpClient = HttpClientBuilder.create().build();
    
            BasicResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpClient.execute(httpGet, responseHandler);
    

    This one do exactly what I need, but its in my server side, in Java. I need to put this in my app.
    Any idea?

  • sylmosssylmoss BRMember ✭✭

    @amolbadhe it didn't work here :(

    I need to do the equivalent of this java code:

    HttpGet httpGet = new HttpGet("https://iid.googleapis.com/iid/info/" + userToken + "?details=true");
    
            // Header setzen
            httpGet.setHeader("Content-Type", "application/json");
            httpGet.setHeader("Authorization", "key=" + FCM_SERVER_KEY);
    
            HttpClient httpClient = HttpClientBuilder.create().build();
    
            BasicResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpClient.execute(httpGet, responseHandler);
    

    Any idea? Now I'm trying this one, and I get the authorization error as response

    using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", serverKey);
    
                using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        //httpRequestMessage.Headers.Add("Authorization", Convert.ToBase64String(convertStringtoByteArray("key", serverKey)));
    
                        using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                        {
                            string readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            DependencyService.Get<IFCMTopics>().setInformation(readHttpResponse);
                        }
                    }
                }
    
  • sylmosssylmoss BRMember ✭✭

    Now I'm trying this one, but I'm getting "Missing Authorization" error. I tried to put authorization everywhere I could but nothing works

    using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", serverKey);
    
                using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        //httpRequestMessage.Headers.Add("Authorization", Convert.ToBase64String(convertStringtoByteArray("key", serverKey)));
    
                        using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                        {
                            string readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            DependencyService.Get<IFCMTopics>().setInformation(readHttpResponse);
                        }
                    }
                }
    
  • sylmosssylmoss BRMember ✭✭

    Now I'm trying this one, but I'm getting "Missing Authorization" error. I tried to put authorization everywhere I could but nothing works

    using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", serverKey);
    
                using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        //httpRequestMessage.Headers.Add("Authorization", Convert.ToBase64String(convertStringtoByteArray("key", serverKey)));
    
                        using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                        {
                            string readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            DependencyService.Get<IFCMTopics>().setInformation(readHttpResponse);
                        }
                    }
                }
    
  • Esaavedra89Esaavedra89 USMember ✭✭

    @amolbadhe said:
    The HttpClient class can set the Authorization header value on the HttpClient.DefaultRequestHeaders.Authorization property. Hope Below code will help you.

      public HttpClientHandler Handler { get; set; } = new NativeMessageHandler();
    
      public async void GetAsyncRequestCall()
      {
          var httpClient = new HttpClient(Handler);
          httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          httpClient.DefaultRequestHeaders.Add("APP_VERSION", "1.0.0");
          httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_authorization_token_string");
          HttpResponseMessage response = await httpClient.GetAsync("https://example.com/xyz");
          var result = response.Content.ReadAsStringAsync().Result;;
    
      }
    

    Excellent, works for me.

  • NajilathNajilath Member ✭✭

    Iam tried this one, but I'm getting "code": 401, "message": "Authentication required"

  • NajilathNajilath Member ✭✭

    I tried
    public HttpClientHandler Handler { get; set; } = new NativeMessageHandler();

    public async void GetAsyncRequestCall()
    {
    var httpClient = new HttpClient(Handler);
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Add("APP_VERSION", "1.0.0");
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_authorization_token_string");
    HttpResponseMessage response = await httpClient.GetAsync("https://example.com/xyz");
    var result = response.Content.ReadAsStringAsync().Result;;

    }
    but authorization_token not accepting

  • ketanravatketanravat Member ✭✭

    hello @sylmoss and @Najilath you can try below method and it works for me!!

    public static string URL = "Your URL";
    var baseaddr = new Uri(URL);
    var client = new HttpClient { BaseAddress = baseaddr };
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer"," your api token");
    var response = client.GetStringAsync(command).Result;

    and also if you are testing on android 9 or above you need to add below line in to androidmenifast file in to application tag.

    android:usesCleartextTraffic="true"

  • NajilathNajilath Member ✭✭

    Exception:System.Net.WebException: 'The remote server returned an error: (401) UNAUTHORIZED.'
    how to solve ?

    OAuthRequest client = OAuthRequest.ForClientAuthentication("Consumer Key", "Consumer Secret", "Access Token", "Token Secret");
            client.RequestUrl = "https://.......";
            string auth = client.GetAuthorizationHeader();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);
    
             request.Headers.Add ("Authorization", auth);
    
    
    
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
Sign In or Register to comment.