我使用的API要求我将方法设置为GET并包含消息正文。但是,当我尝试执行此操作时,出现以下错误:“无法使用此动词类型发送内容主体”。我读到HttpWebRequest类不支持此功能,这是导致异常的原因。有没有解决的办法?
这是我当前的代码:data是一个编码为字节数组的json字符串
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream()) {
requestStream.Write(data.ToArray(), 0, (int)data.Length);
}
Run Code Online (Sandbox Code Playgroud)
这是我试图模仿的PHP代码
<?php
$data = array("id" => "1234");
$data_string = json_encode($data);
$ch = curl_init('url');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
var_dump($result);
?>
Run Code Online (Sandbox Code Playgroud)
谢谢,
主动违背 REST 的 API 被称为什么?“急”?“忧虑”?
幸运的是,他们的服务并不关心动词是什么,PHP 代码恰好使用 GET 并遇到了服务器没有阻止它的错误,只要它行为正确,这就是一个相当小的错误,用 POST 就可以了。
如果做不到这一点,您最好的选择是看看他们是否有替代方法(如果它是自然适合 GET 的读取请求)接受 URI 中的参数,并且可能按照 RFC 2616 使用适当的标头,或者可以通过以下方式接受某些内容:发布、获取等
如果这不起作用,您必须在 TcpClient 之上构建一个 HTTP 客户端。这将是非常可怕的。