0
votes

I am using HttpClient to send the data to the server through C# console application using post . The HttpClient PostAsync is unable to post the data I have tried to send in various format i.e string content , binary content , stream content , http content through Dictionary object but the post is null and the server is returning the request invalid exception below is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Web;


namespace ConsoleApplication1
{
    class Program
    {
        string str = ""; int j = 0;
        static void Main(string[] args)
        {
            Program df = new Program();

            df.Started();

        }


         public async void Started()
         {
             string contentLength="0";
             try
             {
                 contentLength = await AccessTheWebAsync();
             }
             catch (Exception e)
             {

             }


             Console.WriteLine(contentLength);
         }

        async Task<string> AccessTheWebAsync()
        {  
            HttpClient client = new HttpClient();

            string token =  "qwerty1234";
            string test = "1";
            string postrequest = "<?xml version='1.0' encoding='UTF-8'?>" +
                              "<request> " +
                              "<rec>asdf1234</rec> " +
                              " <lid>9876</lid> " +
                              "</request> ";


            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("token", token);
            dict.Add("test", test);
            dict.Add("request", postrequest);

            HttpContent content = new FormUrlEncodedContent(dict);

            Uri url = new Uri("http://example.com/"); 

            Task<HttpResponseMessage> getStringTask = client.PostAsync(url, content);    

            HttpResponseMessage httpmesssage = await getStringTask;
            Stream respons = await httpmesssage.Content.ReadAsStreamAsync();
            StreamReader sr = new StreamReader(respons);
            string response =  sr.ReadToEnd();
            return response;

        }



        }

}

thanks in advance

1
Have you looked at what's happening at the HTTP level via Wireshark or Fiddler? - Jon Skeet

1 Answers

0
votes

In a Console application, you need to wait for the operation to complete, either using Task.Wait, Console.ReadKey, or similar. Also, avoid async void:

static void Main(string[] args)
{
    Program df = new Program();
    df.StartedAsync().Wait();
}

public async Task StartedAsync()