Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get 411 Length required error?

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?

like image 986
markzzz Avatar asked Aug 21 '13 08:08

markzzz


People also ask

How do I fix my 411 Length?

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 response code?

What Is a 411 Status Code? The server refuses to accept the request without a defined Content-Length1.

Is content Length required?

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.

How do I add content Length to my header?

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.


2 Answers

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; 
like image 90
Atlasmaybe Avatar answered Oct 05 '22 13:10

Atlasmaybe


you need to add Content-Length: 0 in your request header.

a very descriptive example of how to test is given here

like image 24
Ehsan Avatar answered Oct 05 '22 15:10

Ehsan