Solving 400 Bad Request when using WebRequest with Twitter

If you are building an app to talk to the Twitter API then you might have come across a stumbling block when making some calls using the .NET HttpWebRequest object. On some commands you’ll get the HTTP response code “400 Bad Request” – I hit this with the /friendships/create/ API call.

This could be for one of (at least) two reasons:

  • Wrong Request Method – some API calls are pretty fussy about whether you’re making a POST or a GET request. If you get the wrong one, you’ll get response code 400. You can see which commands require which kind of request in the Twitter API documentation.
  • Exceeded API Limit – Twitter will only let you make a set number of calls within a set amount of time. Once you’re over that limit, you’ll get “400 Bad Request”.

Working out which issue you’re seeing is quite easy. The error you get will be in the form of a WebException, containing a Response object. The Response object headers will tell you how many API requests you’ve got left:

An example of a Twitter 400 Bad Request message in C

In the example above you can see that X-RateLimit-Limit is 100, and X-RateLimit-Remaining is zero. I’ve run out of API credit.

If the problem isn’t your API limit quota then you need to look at the type of request you’re making. Each command listed in the Twitter API documentation tells you whether you should make a POST or a GET, and POSTs aren’t quite as simple as putting requestObject.Method = "POST";.

The following (simplified) code makes a POST request, along with supplying the necessary Twitter credentials for API authentication:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create
				("http://twitter.com/APICallURLGoesHere");

string Credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes
				("TwitterUserNameHere:TwitterPasswordHere"));
request.Headers.Add("Authorization", "Basic " + Credentials);
request.Method = "POST";
request.ContentType = "application/xml";
request.AllowWriteStreamBuffering = true;
request.UserAgent = "YourAppNameHere";
request.ContentLength = 0;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Note the required ContentType, ContentLength and AllowWriteStreamBuffering parameters – without them the WebRequest object will still make a GET request.

1 Comment

[...] in its search results. It just doesn’t do breaking news particularly brilliantly. But when an average blog post goes from published to position one in a matter of four hours that’s pretty [...]

Leave a comment

Your comment