发送GET请求并收到“无法使用动词类型发送内容主体”的错误提示。

4

我正在尝试发送一个如下所示的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

我在Stack Overflow上读到了另一个相关的帖子,链接在这里:Cannot send a content-body with this verb-type

但是我认为,在我的try块中使用(HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())可以避免这个错误?

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;
        }
    }
}
3个回答

1
我已经找到了解决方法,如果有人在搜索时遇到这个错误,基本上需要使用http POST才能获取请求流:
webRequest.Method = "GET";

需要进行的操作是将其转换为:
webRequest.Method = "POST";

我在这里找到了答案:http://forums.asp.net/t/1706210.aspx?Cannot+send+a+content+body+with+this+verb+type。该链接中提到了无法使用此动词类型发送内容体的错误。

3
这不是解决方案,它只是一个变通办法。你把方法从GET改成了POST。仍然无法发送带有请求正文的GET请求。在无法更改动词类型的情况下,你已经没辙了。 - Stormhashe

0

将 HttpWebRequest 方法从 GET 改为 POST 应该可以解决问题

例如:HttpWebRequest request; request.Method = "POST";


0

只有在请求方法不同于Get时才允许请求内容:

if (request.Method != HttpMethod.Get)
{
    request.Content = ...;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接