You should set read timeout by setReadTimeout. If you got a 504, it means that the connection is ok, but waiting too long to read something from it.
See more here: http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html#setReadTimeout(int)