2016-11-13 192 views
0

我需要发送一个GET请求给期望请求正文中的JSON的服务。我知道GET请求并不意味着以这种方式使用,但我无法控制该服务,并且需要使用现有的API,但是可能会破坏。如何使用C#发送包含JSON正文的GET请求?

所以,这里就是工作:

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() 

有道理。我如何绕过这个?

谢谢!

回答

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); 
     } 
    } 
}