我使用的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)
谢谢,