Java HTTPUrlConnection returns 500 status code

Viewed 28890

I'm trying to GET a url using HTTPUrlConnection, however I'm always getting a 500 code, but when I try to access that same url from the browser or using curl, it works fine!

This is the code

try{
    URL url = new URL("theurl"); 
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpcon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:14.0) Gecko/20100101 Firefox/14.0.1");
    System.out.println(httpcon.getHeaderFields());
    }catch (Exception e) {
        System.out.println("exception "+e);
    }

When I print the headerfields, it shows the 500 code.. when I change the URL to something else like google.com , it works fine. But I don't understand why it doesn't work here but it works fine on the browser and with curl.

Any help would be highly appreciated..

Thank you,

8 Answers

This is an old question, but I have had same issue and solved it this way.

This might help other is same situation.

In my case I was developing system on local environment, and every thing worked fine when I checked my Rest Api from browser but I got all the time thrown HTTP error 500 in my Android system.

The problem is when you work on Android, it works on VM (Virtual Machine), that said it means your local computer firewall might preventing your Virtual Machine accessing the local URL (IP) address.

You need just to allow that in your computer firewall. The same thing apply if you trying to access system from out side your network.

Check the parameter

httpURLConnection.setDoOutput(false);

Only for GET Method and set to true on POST, this save me lot of time!!!

Related