Month: October 2015

Android HttpUrlConnection- “Bad Request” problem in Older Version of Android


I was using HttpUrlConnection for a project, everything was working perfectly. One fine day, I saw a crash report(it was related to some other functionality though – I’ve added @Target annotation to a method but forgot to write logic to handle lower versions) generated from a Android 2.3 device. I started an emulator for 2.3 and started testing the App.

Suddenly, Login functionality started misbehaving. I was getting bad request response. I’ve been testing the App only on 4.0+ devices until then. The error came as a sudden blow in my face. I’ve tested it on 3.1 emulator, got the same issue. I got tensed, and tested it on 4.3 emulator, app was working perfectly fine. With this I clearly understood that the problem is with android version compatibility.

Upon investigation, I found that the culprit is HttpUrlConnection. It is lacking consistency across different versions of android(particularly 2.x). I came across a several posts on similar issues in StackOverflow. After going through some solutions, decided to log headers and check. I noticed that “Host” header was missing. I’ve just added it and peace got restored!

Points to Note: Beware of HttpUrlConnection. I’ve tested my code on a device which had gingerbread initially, later rooted and installed ICS. I was not able to send parameters in “POST” request. Issue was HOST header was missing in the request. After adding that header to requests, app is working normally again.