我需要向请求体中需要JSON的服务发送GET请求。我理解GET请求并不是以这种方式使用,但是我无法控制服务,需要使用现有的API,但可能会有所破坏。
所以,
var req = (HttpWebRequest)WebRequest.Create("localhost:3456");
req.ContentType = "application/json";
req.Method = "GET";
using (var w = new StreamWriter(req.GetRequestStream()))
w.Write(JsonConvert.SerializeObject(new { a = 1 }));
失败了:
Unhandled Exception: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
at System.Net.HttpWebRequest.CheckProtocol(Boolean onRequestStream)
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
有道理。我该如何绕过这个?
谢谢!
答案 0 :(得分:1)
这似乎唯一的方法就是直接使用TcpClient,这就是我所做的。以下是一些适合我的示例源代码:
using (var client = new TcpClient(host, port))
{
var message =
$"GET {path} HTTP/1.1\r\n" +
$"HOST: {host}:{port}\r\n" +
"content-type: application/json\r\n" +
$"content-length: {json.Length}\r\n\r\n{json}";
using (var network = client.GetStream())
{
var data = Encoding.ASCII.GetBytes(message);
network.Write(data, 0, data.Length);
using (var memory = new MemoryStream())
{
const int size = 1024;
var buf = new byte[size];
int read;
do
{
read = network.Read(buf, 0, buf.Length);
memory.Write(buf, 0, read);
} while (read == size && network.DataAvailable);
// Note: this assumes the response body is UTF-8 encoded.
var resp = Encoding.UTF8.GetString(memory.ToArray(), 0, (int) memory.Length);
return resp.Substring(resp.IndexOf("\r\n\r\n", StringComparison.Ordinal) + 4);
}
}
}