Search code examples
c#webclient

POSTing JSON to URL via WebClient in C#


I have some JavaScript code that I need to convert to C#. My JavaScript code POSTs some JSON to a web service that's been created. This JavaScript code works fine and looks like the following:

var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
  url: "http://www.mysite.com/1.0/service/action",
  type: "POST",
  data: JSON.stringify(vm),
  contentType: "application/json;charset=utf-8",
  success: action_Succeeded,
  error: action_Failed
});

function action_Succeeded(r) {
  console.log(r);
}

function log_Failed(r1, r2, r3) {
  alert("fail");
}

I'm trying to figure out how to convert this to C#. My app is using .NET 2.0. From what I can tell, I need to do something like the following:

using (WebClient client = new WebClient())
{
  string json = "?";
  client.UploadString("http://www.mysite.com/1.0/service/action", json);
}

I'm a little stuck at this point. I'm not sure what json should look like. I'm not sure if I need to set the content type. If I do, I'm not sure how to do that. I also saw UploadData. So, I'm not sure if I'm even using the right method. In a sense, the serialization of my data is my problem.

Can someone tell me what I'm missing here?

Thank you!


Solution

  • 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,