为什么我得到411长度所需错误? [英] Why I get 411 Length required error?

查看:985
本文介绍了为什么我得到411长度所需错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我如何调用使用.NET服务:

This is how I call a service with .NET:

var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
WebResponse authResponseTwitter = authRequest.GetResponse();



但调用此方法时,我得到:

but when this method is invoked, I get:

异常详细信息:System.Net.WebException:远程服务器返回
错误:(411)所需的长度

Exception Details: System.Net.WebException: The remote server returned an error: (411) Length Required.

我应该怎么办?

推荐答案

当你使用HttpWebRequest和POST方法,你必须通过RequestStream(如果你喜欢或身体)设置内容。但是,根据你的代码,使用authRequest.Method =GET应该够了。

When you're using HttpWebRequest and POST method, you have to set a content (or a body if you prefer) via the RequestStream. But, according to your code, using authRequest.Method = "GET" should be enough.

在如果你想知道关于POST格式,这里是你必须做的事

In case you're wondering about POST format, here's what you have to do :

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";

request.GetRequestStream().Write(data, 0, data.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

这篇关于为什么我得到411长度所需错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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