Alex Rivera | Logout

Java HTTPUrlConnection returns 500 status code

Asked 2012-07-30T12:41:51.160
8

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,

Edit
Report

1 Answer

1

Make sure that your connection allows following redirects - this is one of the possible reasons for difference in behaviour between your connection and the browser (allows redirect by default).

It should be returning code 3xx, but there maybe something else somewhere that changes it to 500 for your connection.

answered 2012-07-30T12:57:40.817

Your Answer