首页 文章

在C#中通过WebClient将JSON发布到URL

提问于
浏览
72

我有一些我需要转换为C#的JavaScript代码 . 我的JavaScript代码将一些JSON发布到已创建的Web服务 . 此JavaScript代码工作正常,如下所示:

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");
}

我正在试图找出如何将其转换为C# . 我的应用程序使用的是.NET 2.0 . 据我所知,我需要做以下事情:

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

我'm a little stuck at this point. I'我不确定 json 应该是什么样的 . 我'm not sure if I need to set the content type. If I do, I'我不知道该怎么做 . 我也看到了 UploadData . 所以,即使使用正确的方法,我'm not sure if I' m . 从某种意义上说,我的数据序列化是我的问题 .

谁能告诉我我在这里失踪了什么?

谢谢!

3 回答

  • 58

    您需要一个json序列化程序来解析您的内容,可能是您已经拥有它,以获取有关如何发出请求的初始问题,这可能是一个想法:

    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();
    

    希望能帮助到你,

  • 62

    问题已经得到解答,但我认为我找到的解决方案更简单,与问题 Headers 更相关,这里是:

    var cli = new WebClient();
    cli.Headers[HttpRequestHeader.ContentType] = "application/json";
    string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
    
  • 165

    以下示例演示如何通过WebClient.UploadString Method发布JSON:

    var vm = new { k = "1", a = "2", c = "3", v=  "4" };
    using (var client = new WebClient())
    {
       var dataString = JsonConvert.SerializeObject(vm);
       client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
       client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
    }
    

    先决条件:Json.NET库

相关问题