在 C# 中通过 WebClient 将 JSON POST 到 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15091300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:01:16  来源:igfitidea点击:

POSTing JSON to URL via WebClient in C#

c#webclient

提问by Eels Fan

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:

我有一些需要转换为 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");
}

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:

我想弄清楚如何将其转换为 C#。我的应用程序使用 .NET 2.0。据我所知,我需要执行以下操作:

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 jsonshould 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.

我在这一点上有点卡住了。我不确定json应该是什么样子。我不确定是否需要设置内容类型。如果我这样做,我不知道该怎么做。我也看到了UploadData。所以,我不确定我是否使用了正确的方法。从某种意义上说,我的数据的序列化是我的问题。

Can someone tell me what I'm missing here?

有人可以告诉我我在这里缺少什么吗?

Thank you!

谢谢!

采纳答案by Jorge Alvarado

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:

您需要一个 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();

hope it helps,

希望能帮助到你,

回答by sarh

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

问题已经回答,但我想我找到了更简单且与问题标题更相关的解决方案,这里是:

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

回答by Vadim Gremyachev

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

以下示例演示如何通过WebClient.UploadString 方法POST 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);
}

Prerequisites: Json.NET library

先决条件:Json.NET 库