Posting JSON to Url via Webclient in C#

POSTing JSON to URL via WebClient in C#

You need a json serializer to parse your content, probably you already have it,
for your initial question on how to make a request, this might be an idea:

var baseAddress = "http://www.example.com/1.0/service/action";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

C# WebClient upload JSON in POST request

Someone answered this question already but their answer was removed for some reason. Their solution was valid, however, so I've thrown together a rough implementation of it below (it's not at all dynamic but it should help others who have a problem similar to mine):

using (WebClient Client = InitWebClient())
{

List<MyJsonObject> Items = new List<MyJsonObject>();

// The following could easily be made into a for loop, etc:
MyJsonObject Item1 = new MyJsonObject() {
Id = 0,
Name = "John"
};
Items.Add(Item1);
MyJsonObject Item2 = new MyJsonObject() {
Id = 1,
Name = "James"
};
Items.Add(Item2);

string Json = Newtonsoft.Json.JsonConvert.SerializeObject(Items)
Client.Headers[HttpRequestHeader.ContentType] = "application/json";
Client.UploadValues("/api/example", "POST", Json);

}

Here is the object that will be serialized:

public class MyJsonObject {
public int Id { get; set; }
public string Name { get; set; }
}

POST JSON to webservice using WebClient C#

Finally I got the solution with help of fiddler. Thanks to Jasen for suggesting fiddler to see requests

Here is my working code

WebClient client = new WebClient();
string result = client.UploadValues("http://Server.com/MyService/Account/Register", new NameValueCollection()
{
{"Name","Lorem"},
{"Email","abc@abc.com"},
{"interest","[\"1\"]"},
{"sectors","[\"1\",\"2\"]"},
{"interest","false"}
});

Yes I used UploadValues method instead of UploadData or UploadString. Also note that I have removed the content type json declaration from my code.

Upload JSON via WebClient

Figured it out. I was forgetting the following:

myService.Headers.Add("Content-Type", "application/json");

How to post data to specific URL using WebClient in C#

I just found the solution and yea it was easier than I thought :)

so here is the solution:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";

using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}

it works like charm :)

How to post JSON to a server using C#?

The way I do it and is working is:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";

streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest

C# WebClient using UploadString to call HttpPost method from an ApiController also in C#. 415 or 400 error

I'm getting
System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'

When you use [FromBody], the Content-Type header is used in order to determine how to parse the request body. When Content-Type isn't specified, the model-binding process doesn't know how to consume the body and therefore returns a 415.

I get System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'

By setting the Content-Type header to application/json, you're instructing the model-binding process to treat the data as JSON, but ABC itself isn't valid JSON. If you just want to send a JSON-encoded string, you can also wrap the value in quotes, like this:

client.UploadString("https://localhost:44345/api/Test", "\"ABC\"");

"ABC" is a valid JSON string and will be accepted by your ASP.NET Core API.



Related Topics



Leave a reply



Submit