发送 GET 请求和获取无法发送动词类型的内容正文

Joh*_*ohn 4 .net get webrequest

我正在尝试发送一个 GET 请求,如下所示,但我不断收到控制台上的以下错误:

Test_API_Access.Exception:Cannot send a content-body with this verb-type.
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()
   at Test_API_Access.Program.Test_API_Access() in c:\Users\<username>\Documents\Visual Studio 2013\Projects\Test_API_Access\Test_API_Access\Program.cs:line 43
Run Code Online (Sandbox Code Playgroud)

我阅读了另一个关于堆栈溢出的相关线程,这里提到:无法发送具有此动词类型的内容正文

但我想,我一直(HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())在我的 try 块中使用 using可以避免这个错误吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Runtime.Serialization;
using System.IO;
namespace Test_API_Access
{ class Program
   {  static void Main(string[] args)
      { Test_API_Access();}
      private static void Test_API_Access()
       {  var publicKey = "publickeygoeshere";
          var privateKey = "privatekeygoeshere";
          var MyDateTime = DateTime.UtcNow.ToString();
          var stringToSign = "POST" + "\n\n\n" + MyDateTime + "\n\n\n";
          var signature = HmacSha1SignRequest(privateKey, stringToSign.ToString());
          var resTreq = new StringBuilder();
          var Url = "https://exvvii.com/webservice/testapi/123456";
          try
           {  // make web service call
              byte[] dataStream = Encoding.UTF8.GetBytes(resTreq.ToString());
              var webRequest = WebRequest.Create(Url);
              webRequest.Method = "GET";
              webRequest.ContentType = "application/x-www-form-urlencoded";
              webRequest.ContentLength = dataStream.Length;
              webRequest.Headers["datetime"] = MyDateTime;
              webRequest.Headers["Authorization"] = publicKey + ":" + signature;
              var newStream = webRequest.GetRequestStream();  // THIS IS LINE #43
              newStream.Write(dataStream, 0, dataStream.Length);
              long length = 0;
              try
              {  using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                    {   length = response.ContentLength;
                        var header = response.GetResponseStream();
                        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                        StreamReader readStream = new StreamReader(header, encode);
                        Char[] read = new Char[256];
                        // Reads 256 characters at a time.
                        int count = readStream.Read(read, 0, 256);
                        while (count > 0)
                        { // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(read, 0, count);
                        Console.Write(str);
                        count = readStream.Read(read, 0, 256);
                        }
                        Console.WriteLine("");
                        // Releases the resources of the response.
                        response.Close();
                        // Releases the resources of the Stream.
                        readStream.Close();
                    }
                }
                catch (WebException ex)
                {
                    // Log exception and throw as for GET example above
                }
                Console.ReadLine();

            }
            catch (Exception ex)
            {
                Console.WriteLine("Test_API_Access.Exception:" + ex.Message);
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }

        }
        public static string HmacSha1SignRequest(string privateKey, string valueToHash)
        {   System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(privateKey);
            HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
            byte[] messageBytes = encoding.GetBytes(valueToHash);
            byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
            var hashedValue = Convert.ToBase64String(hashmessage);
            return hashedValue;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

dar*_*rin 6

我找到了解决方案,以防有人在搜索时遇到此错误,基本上是为了获取您需要使用 http POST 的请求流:

webRequest.Method = "GET";
Run Code Online (Sandbox Code Playgroud)

需要是

webRequest.Method = "POST";
Run Code Online (Sandbox Code Playgroud)

我在这里找到了答案:http : //forums.asp.net/t/1706210.aspx?Cannot+send+a+content+body+with+this+verb+type

  • 这不是一个解决方案,而是一个解决方法。您将方法从 GET 更改为 POST。您仍然无法发送带有正文的 GET 请求。在无法更改动词类型的情况下,你就完蛋了 (3认同)