1
    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

Skin
  • 9,085
  • 2
  • 13
  • 29
Concellia
  • 15
  • 1
  • 4

1 Answers1

2

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.

Skin
  • 9,085
  • 2
  • 13
  • 29
  • Thank you so much for the assistance but I am still getting the same error, when I try to debug it seems like my code immediately stops at var response = await httpClient.SendAsync(request); it returns the error that I posted when it gets here I am not sure if this has to do with how I am calling it on the main method or is it something to do with my .NET core version. – Concellia Mar 06 '22 at 08:03
  • What’s the endpoint? Maybe I can test from here. – Skin Mar 06 '22 at 08:06
  • Sorry for the late response you can test with this endpoint: "https://bounties-backend-mini-program.herokuapp.com/api/userInfo" you can just pass "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }" as your json data – Concellia Mar 06 '22 at 09:11
  • It came back and I got a success. There's no content in the response body but there are headers, they all look to be pretty standard sort of things though ... [{"Key":"Server","Value":["Cowboy"]},{"Key":"Connection","Value":["keep-alive"]},{"Key":"X-Powered-By","Value":["Express"]},{"Key":"ETag","Value":["W/\"2-vyGp6PvFo4RvsFtPoIWeCReyIC8\""]},{"Key":"Date","Value":["Sun, 06 Mar 2022 09:41:54 GMT"]},{"Key":"Via","Value":["1.1 vegur"]}] ... must be something to do with your environment then. Sorry I couldn't be anymore help. You may want to recycle your authCode. :-) – Skin Mar 06 '22 at 09:43
  • Thank you the response is right it was just a simple one I made for you to test it does not have any data, which .net core are you using? I am using .Net Core 3.1 and also did you pass the same endpoint here httpClient.BaseAddress and here $"{slash}{urlSuffix}"? – Concellia Mar 06 '22 at 09:48
  • Ah haaaaaa! Maybe that's the problem. Check my answer now, does that work for you? – Skin Mar 06 '22 at 09:50
  • Do you mind pasting the code you used to test maybe I can see where I made a mistake. – Concellia Mar 06 '22 at 09:50
  • Yep, did that. As per the previous comment, I've update my answer. – Skin Mar 06 '22 at 09:51
  • Sorry to bother you again can you please check the above code I have added and see maybe I am calling it wrong or something I literally copied your code but still getting the the same error and thank you you so much for your help so far. – Concellia Mar 06 '22 at 10:17
  • I've updated your question, doing `Console.WriteLine(Post());` will simply not work. Given it's from within the `Main` method and you're calling an async method, you need to use an approach like `.Wait()` to get it to run and finish. I honestly don't know what's going wrong, I feel like you need to share your entire project for someone to be able to download it and see why it's going wrong. – Skin Mar 06 '22 at 10:30