【问题标题】:How to send a GET request containing a JSON body, using C#?如何使用 C# 发送包含 JSON 正文的 GET 请求?
【发布时间】:2016-11-13 23:22:12
【问题描述】:

我需要向请求正文中需要 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()

有道理。如何绕过这个?

谢谢!

【问题讨论】:

    标签: c# json get


    【解决方案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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2018-04-21
      相关资源
      最近更新 更多