繁体   English   中英

如何使用C#发送包含JSON正文的GET请求?

[英]How to send a GET request containing a JSON body, using C#?

我需要将GET请求发送到在请求正文中需要JSON的服务。 我了解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()

说得通。 我该如何绕过?

谢谢!

看来唯一的方法就是直接使用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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM