Home > Software engineering >  How to send a post request in dotnet with a list of request headers
How to send a post request in dotnet with a list of request headers

Time:03-06

    public static async Task<HttpResponseMessage> Post(string endPoint, string data){
        HttpContent c = new StringContent(data, Encoding.UTF8, "application/json");
        using (var client = new HttpClient())
        {
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(VodapayBaseUrl   endPoint),
                Content = c,

            };

            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = await client.SendAsync(request).ConfigureAwait(false); // The code fails here

            if (result.IsSuccessStatusCode)
            {
                
                Console.WriteLine("got here");
                return result;
            }
            else
            {
                Console.WriteLine("failled");
                return result;
            }
        }
          
       // return result;
        
    }

Here is an updated version:

public static async Task Post()
    {
        using (var httpClient = new HttpClient())
        {
            var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";

            httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
            request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");

            var response = await httpClient.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Successful");
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine("Not successful");
            }
        }


    }

    class Program
    {

        private static void Main(string[] args)
        {
           
            Post().Wait();
            Console.WriteLine();

        }
    }
}

Can someone please help with this I am new to c# and relatively new to coding. I am trying to send a request using httpclient I need to send data in a json format I also need to send a list of headers. How can I do this and also return json data at the end your help will be appreciated.I am getting an error when i run this:

enter image description here

CodePudding user response:

Your code isn't far off, here's an example that I had in one of my projects ...

using (var httpClient = new HttpClient())
{
    var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";

    // Setup the HttpClient and make the call and get the relevant data.
    httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
    request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");

    var response = await httpClient.SendAsync(request);
    var responseContent = await response.Content.ReadAsStringAsync();

    Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));

    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Successful");
        Console.WriteLine(responseContent);
    }
    else
    {
        Console.WriteLine("Not successful");
    }
}

... obviously, it has varying degrees of thought for the scenario at hand but just adapt it as need be.

  • Related