POST操作JSON通过在C#中的WebClient URL [英] POSTing JSON to URL via WebClient in C#
问题描述
我有一些JavaScript code,我需要转换为C#。我的JavaScript code的POST一些JSON到一个已经创建了一个Web服务。这个JavaScript code工作正常,如下所示:
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");
}
我试图找出如何将其转换为C#。我的应用程序是使用.NET 2.0。从我可以告诉,我需要做类似如下:
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);
}
我有点停留在这一点上。我不知道是什么 JSON
应该像。我不知道我是否需要设置的内容类型。如果我这样做,我不知道该怎么做。我也看到 UploadData code>。所以,我不知道如果我即使使用正确的方法。从某种意义上说,我的数据的序列化是我的问题。
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?
感谢您!
推荐答案
您需要一个JSON序列来分析你的内容,很可能你已经拥有它,
您如何使一个请求最初的问题,这可能是一个想法:
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.mysite.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();
希望它帮助,
这篇关于POST操作JSON通过在C#中的WebClient URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!