我需要一个不依赖于 HttpWebRequest 的 C# HTTP 库,因为我无法从运行代码所需的环境(Unity 的 WebPlayer)访问它。
理想情况下,这应该是轻量级的,但欢迎提出任何建议!
我只需要能够执行简单的 HTTP GET 和 POST 请求,但更好的 REST 支持会更好。
谢谢!
编辑:正如人们所指出的,HttpWebRequest 不在 System.Web 中,但事实仍然存在——我无法使用它。我已经更新了上面的帖子。
这篇文章 http://forum.unity3d.com/threads/24445-NotSupportedException-System.Net.WebRequest.GetCreator显示我遇到的相同错误。
最佳答案
使用 Socket 实现您自己的简单 HTTP 客户端并不难。
只需使用 TcpClient()。
对于协议(protocol)本身,下降到每个请求连接的范例。典型的 GET 请求如下所示:
GET /url HTTP/1.1
Host: <hostname-of-server>
Connection: close
对于代码本身(来自内存)
TcpClient client = new TcpClient();
IPEndPoint target = ... // get an endpoint for the target using DNS class
client.Connect(target);
using(NetworkStream stream = client.GetStream())
{
// send the request.
string request = "GET /url HTTP/1.1\r\nConnection: close\r\n\r\n";
stream.Write(Encoding.ASCII.GetBytes(request));
// then drain the stream to get the server response
}
请注意,您需要使用一个提供类似 HTTPWebRequest 语义的简单类来包装此代码。
关于c# - 不依赖于 HttpWebRequest 的 HTTP 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568037/