我使用的 API 要求我将方法设置为 GET 并包含消息正文。但是,当我尝试执行此操作时,出现以下错误:“无法发送具有此动词类型的内容主体”。我读到 HttpWebRequest 类不支持这一点,这是异常的原因。有解决办法吗?
这是我当前的代码:数据是一个 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);
}
这是我试图模拟的 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);
?>
谢谢,