0

I am trying to connect to an API using HttpClient but when I try to I get the error Cannot send a content-body with this verb-type.

I have copied the code from Postman where it works ok but not in a C# .net windows form app.

Also if I comment out the content.headers.ContentType part I get this error

Response status code does not indicate success: 415 (Unsupported Media Type).

What Am I missing?

try
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "https://connect1.uat.westpac.co.nz/fxrates/v1/forexratesheet/v2");
            request.Headers.Add("X-IBM-Client-Id", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx");
            request.Headers.Add("X-IBM-Client-Secret", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            request.Headers.Add("accept", "application/json");

            var content = new StringContent(string.Empty);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            this.txtResult.Text = await response.Content.ReadAsStringAsync();
            //Console.WriteLine(await response.Content.ReadAsStringAsync());
        }

        catch (Exception ex)
        {
            this.txtResult.Text = ex.Message;
        }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Matt frost
  • 11
  • 1
  • 1
    Get requests usually don’t contain a body – Daniel A. White Jul 10 '23 at 23:30
  • 1
    The 'verb-type' you have is a `GET`. If you want to send content to the server use `POST` (or `PUT`). (See [HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) and the [`HttpMethod`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod?view=net-7.0) class.). – Jonathan Dodds Jul 10 '23 at 23:48
  • 1
    Does this answer your question? [How to use HttpClient to send content in body of GET request?](https://stackoverflow.com/questions/43421126/how-to-use-httpclient-to-send-content-in-body-of-get-request) – James G Jul 10 '23 at 23:57

0 Answers0