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

我有一些 JavaScript 代码需要转换成 C # 。我的 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);
}

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

有人能告诉我我错过了什么吗?

谢谢!

204942 次浏览

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,

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

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

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

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