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:
Exception Details: System.Net.WebException: The remote server returned an error: (411) Length Required.
what should I do?
Fortunately, you can easily fix the “411 Length Required” error. This HTTP status code happens when the server requires a content-length header, but it isn't specified in a request. To resolve this issue, you can simply define a content length.
What Is a 411 Status Code? The server refuses to accept the request without a defined Content-Length1.
The Content-Length is optional in an HTTP request. For a GET or DELETE the length must be zero. For POST, if Content-Length is specified and it does not match the length of the message-line, the message is either truncated, or padded with nulls to the specified length.
To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.
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.
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;
you need to add Content-Length: 0
in your request header.
a very descriptive example of how to test is given here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With