WebRequest 是与网站交互的正确 C# 工具吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/91275/
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
Is WebRequest The Right C# Tool For Interacting With Websites?
提问by
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.
我正在用 C# 编写一个小工具,它需要使用 POST 和 json 格式向/从网站发送和接收数据。我以前从未在 C#(或任何语言)中做过这样的事情,所以我正在努力寻找一些有用的信息来帮助我入门。
I've found some information on the WebRequest class in C# (specifically from here) but before I start diving into it, I wondered if this was the right tool for the job.
我在 C# 中找到了关于 WebRequest 类的一些信息(特别是从这里),但在我开始深入研究它之前,我想知道这是否是适合这项工作的工具。
I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
我发现有很多工具可以将数据转换为 json 格式,但其他工具不多,所以如果我最终陷入死胡同,任何信息都会非常有用。
采纳答案by Wolfwyrd
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like:
WebRequest,更具体地说,HttpWebRequest 类是您想要实现的目标的良好起点。要创建请求,您将使用 WebRequest.Create 并将创建的请求转换为 HttpWebRequest 以实际使用它。然后,您将创建您的帖子数据并将其发送到流中,例如:
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://mysite.com/index.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "var=value1&var2=value2";
req.ContentLength = postData.Length;
StreamWriter stOut = new
StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at:
同样,您可以使用 GetResponse 方法读取响应,该方法将允许您读取结果响应流并执行您需要执行的任何其他操作。您可以在以下位置找到有关该课程的更多信息:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
回答by Seb Rose
I have used WebRequest for interacting with websites. It is the right 'tool'
我已经使用 WebRequest 与网站进行交互。这是正确的“工具”
I can't comment on the JSON aspect of your question.
我无法评论您问题的 JSON 方面。
回答by redsquare
in 3.5 there is a built-in jsonserializer. The webrequest is the right class your looking for.
在 3.5 中有一个内置的 jsonserializer。webrequest 是您正在寻找的正确类。
A few examples:
几个例子:
回答by Eric Schoonover
WebClientis sometimes easier to use than WebRequest. You may want to take a look at it.
WebClient有时比WebRequest更容易使用。你可能想看看它。
For JSON deserialization you are going to want to look at the JavaScriptSerializerclass.
对于 JSON 反序列化,您需要查看JavaScriptSerializer类。
WebClient example:
网络客户端示例:
using (WebClient client = new WebClient ())
{
//manipulate request headers (optional)
client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
//execute request and read response as string to console
using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
{
string s = reader.ReadToEnd ();
Console.WriteLine (s);
}
}
Marked as wiki in case someone wants to update the code
标记为 wiki 以防有人想要更新代码
回答by mdb
When it comes to POSTing data to a web site, System.Net.HttpWebRequest(the HTTP-specific implementation of WebRequest) is a perfectly decent solution. It supports SSL, async requests and a bunch of other goodies, and is well-documented on MSDN.
在将数据发布到网站时,System.Net.HttpWebRequest(WebRequest 的 HTTP 特定实现)是一个完美的解决方案。它支持 SSL、异步请求和一堆其他好东西,并且在 MSDN 上有详细记录。
The payload can be anything: data in JSON format or whatever -- as long as you set the ContentType property to something the server expects and understands (most likely application/json, text/json or text/x-json), all will be fine.
有效负载可以是任何内容:JSON 格式的数据或其他格式的数据——只要您将 ContentType 属性设置为服务器期望和理解的内容(很可能是 application/json、text/json 或 text/x-json),所有内容都将是美好的。
One potential issue when using HttpWebRequest from a system service: since it uses the IE proxy and credential information, default behavior may be a bit strange when running as the LOCALSYSTEM user (or basically any account that doesn't log on interactively on a regular basis). Setting the Proxy and Authentication properties to Nothing
(or, as you C# folks prefer to call it, null
, I guess) should avoid that.
从系统服务使用 HttpWebRequest 时的一个潜在问题:由于它使用 IE 代理和凭据信息,因此当以 LOCALSYSTEM 用户(或基本上任何不定期交互登录的帐户)运行时,默认行为可能有点奇怪)。将 Proxy 和 Authentication 属性设置为Nothing
(或者,正如您 C# 的人喜欢称呼它null
,我猜)应该避免这种情况。
回答by Jay
To convert from instance object to json formatted string and vice-versa, try out Json.NET: http://json.codeplex.com/
从实例对象转换成JSON格式的字符串,反之亦然,尝试Json.NET: http://json.codeplex.com/
I am currently using it for a project and it's easy to learn and work with and offers some flexibility in terms of serializing and custom type converters. It also supports a LINQ syntax for querying json input.
我目前正在将它用于一个项目,它易于学习和使用,并在序列化和自定义类型转换器方面提供了一些灵活性。它还支持用于查询 json 输入的 LINQ 语法。
回答by Michael Maddox
The currently highest rated answer is helpful, but it doesn't send or receive JSON.
当前评分最高的答案很有帮助,但它不会发送或接收 JSON。
Here is an example that uses JSON for both sending and receiving:
这是一个使用 JSON 进行发送和接收的示例:
How to post json object in web service
And here is the StackOverflow question that helped me most to solve this problem:
这是对我解决这个问题最有帮助的 StackOverflow 问题:
Problems sending and receiving JSON between ASP.net web service and ASP.Net web client
在 ASP.net Web 服务和 ASP.Net Web 客户端之间发送和接收 JSON 的问题
And here is another related question:
这是另一个相关的问题: