具有GET方法的C#HTTP正文 [英] C# HTTP Body with GET method

查看:475
本文介绍了具有GET方法的C#HTTP正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的API要求我将方法设置为GET并包含消息正文.但是,当我尝试执行此操作时,出现以下错误:无法发送具有此动词类型的content-body".我读到HttpWebRequest类不支持此功能,这是导致异常的原因.有解决方法吗?

I'm using an API that requires me to set the method to GET and include a message body. However when I try to do this I get the following error: "Cannot send a content-body with this verb-type". I read that the HttpWebRequest class does not support this and is the reason for the exception. Is there a work around?

这是我当前的代码:data是一个编码为字节数组的json字符串

This is my current code: data is a json string encoded as a byte array

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代码

This is the PHP code I'm trying to emulate

<?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);
?>

谢谢

推荐答案

人们怎么称呼一种主动与REST相抵触的API? 急"? "DISQUIET"?

What does one call an API that actively goes against REST? "HASTE"? "DISQUIET"?

幸运的是,他们的服务只是不在乎动词是什么,PHP代码正巧使用GET并遇到了服务器未阻止它的错误,只要它的行为正确,并且可以在POST中正常使用.

With a bit of luck they service just doesn't care what the verb is and the PHP code was just happening to use GET and hit the bug that the server didn't block it which is a pretty minor bug as long as it behaves correctly, and it'll be fine with POST.

如果失败,最好的选择是看他们是否有另一种方法(如果是自然适合GET的阅读请求)接受URI中的参数,并且可能按照RFC 2616使用了适当的标头,或者通过POST,GET等接受某些内容.

Failing that, your best bet is to see if they have an alternative method that either (if it's a reading request that naturally fits GET) accepts parameters in the URI with perhaps appropriate headers being used as per RFC 2616, or else can accept something through POST, GET etc.

如果这不起作用,则必须在TcpClient之上构建一个HTTP客户端.这将是非常可怕的.

If that doesn't work, you'll have to build an HTTP client on top of TcpClient. Which would be pretty horrible.

这篇关于具有GET方法的C#HTTP正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆