0

I need to post an object in this format:

POST https://link
{
  "country": "nld",
  "emailaddress": "email@domain.com",
  "phone": "123",
  "notify_url": "https://asd.com"
}

I tried:

 var url = "URL";
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Accept = "*/*";
            httpRequest.Headers["Authorization"] = "Bearer " + apiKey;


            var postData = "country" + Uri.EscapeDataString("hello");
            postData += "emailaddress" + Uri.EscapeDataString("world");
            postData += "phone" + Uri.EscapeDataString("123");
            postData += "notify_url" + Uri.EscapeDataString("d3wq");
            var data = Encoding.ASCII.GetBytes(postData);

            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.ContentLength = data.Length;

            using (var stream = httpRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
 
            HttpWebResponse httpResponse = null;
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
            }
            catch (Exception e) { }

But the server returns a 400 bad request. I think the data is in invalid format.

How can i alter my code to put the data into correct format ?

Thank you!

Jay
  • 39
  • 5
  • try change to `httpRequest.ContentType= "application/json";` https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c – Александр Инженер Mar 30 '21 at 10:38
  • Usually in authorization headers, a bearer access token is supplied instead of an API key. – Jamshaid K. Mar 30 '21 at 10:38
  • Does this answer your question? [How to post JSON to a server using C#?](https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c) – Self Mar 30 '21 at 10:39
  • https://stackoverflow.com/questions/23585919/send-json-via-post-in-c-sharp-and-receive-the-json-returned – Self Mar 30 '21 at 10:40
  • 1
    @Self holy sh*t there's a lot of bad code being heavily upvoted on this site. Look at the accepted answer on the second Q&A you link to. "`await Task.Run(() => JsonConvert.SerializeObject(payload))`"? Really? `StringContent`, `ReadAsStringAsync()`? The `PostAsJsonAsync()` extension method exists for over six years already. – CodeCaster Mar 30 '21 at 10:42
  • 1
    @CodeCaster, Good catch. I just don't read most of the code. I can find dupe target without reading the question most of the time. I will try to give answers code a better look if theirs numbers is not too big. But a basic search query return too many possible dupe. – Self Mar 30 '21 at 12:21

2 Answers2

3

The example request you show, shows a JSON request body, yet you tell the server in your HttpWebRequest that the incoming content-type is going to be a form post. But then you don't issue a form post, you post one long string:

countryhelloemailaddressworldphone123 // and so on 

Don't use HttpWebRequest in 2021. It's a two decade old API that has more developer-friendly alternatives by now.

Use HttpClient instead, which has convenient (extension) methods for sending and receiving JSON:

var postModel = new
{ 
    country = "...", 
    emailaddress = "...", 
    ... 
}; 

var client = new HttpClient();

var response = await client.PostAsJsonAsync(postModel);

You need to install the Microsoft.AspNet.WebApi.Client NuGet package for that extension method.

If you insist you must use an HttpWebRequest, which I highly doubt, your question is answered in How to post JSON to a server using C#?, as that question and answer shows how to use that ancient API.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Than kyou. For serveral reasons, I have to use the webrequst. Can you show me how its done using this old api? :) – Jay Mar 30 '21 at 10:42
  • is httpclient from system..net.http? cause that one doesnt have postasjsonasync for me... – Jay Mar 30 '21 at 10:48
  • 1
    See https://stackoverflow.com/questions/19158378/httpclient-not-supporting-postasjsonasync-method-c-sharp. It's an extension method in the `Microsoft.AspNet.WebApi.Client` NuGet package. – CodeCaster Mar 30 '21 at 10:49
  • Hello again; i gave urs a try again but I am always getting a bad request: HttpClient client = new HttpClient(); var url = "url"; client.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiKey); var postModel = new { country = "asd", emailaddress = "asd@asd.de", phone = "123456", notify_url = "www.hello.com", }; var response = await client.PostAsJsonAsync(url, postModel); – Jay Mar 30 '21 at 10:59
  • 1
    Then you need to consult said API's documentation to check why it won't accept that payload. – CodeCaster Mar 30 '21 at 11:02
  • I seen that the server receives an empty request. How can it be empty` – Jay Mar 30 '21 at 11:26
  • I don't know. Check the request with Fiddler, and if that contains a payload, debug the server. – CodeCaster Mar 30 '21 at 11:27
  • 1
    Thank you. Working with postman fixed the issue. Appeeantly, the API checked for the input values if they are valid e.g: is this a valid email, is this a valid phone number, etc. That was the last issue I had. Thanks for ur help! – Jay Mar 30 '21 at 12:01
0

Create object that you need to submit on your webrequest.

var xObject = new { xData = ... };

and after that use;

var newJsonData = JsonSerializer.Serialize(xObject);

newJsonData is a string as JSON format which you can post to your webrequest.

H.Sarxha
  • 157
  • 1
  • 9