Search code examples
c#xamarin.net-corexamarin.formshttpclient

Calling Get Request with Json Body using httpclient


I came with an issue this morning where the Api which I am calling is a Get Method but to get Get the Data from it I had to send the json body this is working good when I am testing it in the post man but I am not able to implement it in my project where I am calling this using HttpClient

here is the screenshot of post

enter image description here

It also have a bearer token which I pass in Authorization

Now when I am try to implement this at client side here is my code

  var stringPayload = JsonConvert.SerializeObject(json);
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("https://myapiendpoint/serviceability/"),
            Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
        };
        var response = await client.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

when I call this method using this code I get

System.Net.HttpStatusCode.MethodNotAllowed - Status code 405

I also tried changing this line

 Method = HttpMethod.Get to Method = HttpMethod.Post

but still getting same error

I know this is bad implementation at API Side the request ideally should be POST but changing this is not in my hand and hence need to find the solution


Solution

  • almost search all over and trying all the variant of using GET Method finally the solution which worked for me in this case was this

    var client = new HttpClient();
                client.BaseAddress = new Uri("https://baseApi/");
                client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
                var query = new Dictionary<string, string>
                {
                    ["pickup_postcode"] = 400703,
                    ["delivery_postcode"] = 421204,
                    ["cod"] = "0",
                    ["weight"] = 2,
                };
    
                var url = "methodurl";
                var response = await client.GetAsync(QueryHelpers.AddQueryString(url, query));
                var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                return JsonConvert.DeserializeObject<MyModel>(responseBody);
    

    Got QueryHelpers from Microsoft.AspNetCore.WebUtilities package