So I decided to try out URL connections and requests and whatnot, and I didn't want to use any third-party libraries for my first time, and I am quite confused why it is being very, very inconsistent. The idea was to use wiktionary's api for a dictionary for a small application. However, the URLConnection will seemingly randomly return 0 after the first few calls, and then sometimes get two more useful connections and then back to 0. This might be more clear with a SSCCE to demonstrate the problem.
import java.net.*; import java.io.*; /** * This class is an SSCEE to demonstrate the inconsistency * in the URLConnection class */ public class URLConnectionTest { public static void main(String[] args) throws Exception //No error handling to keep it short and sweet { for(int i = 0; i < 15; i++) { HttpURLConnection connection = (HttpURLConnection)new URL("http://en.wiktionary.org/wiki/amo?action=raw").openConnection(); InputStream in = connection.getInputStream(); System.out.println((i+1)+". Expected bytes = "+in.available()); in.close(); connection.disconnect(); } } }
Average case:
1. Expected bytes = 2896 2. Expected bytes = 0 3. Expected bytes = 0 4. Expected bytes = 0 5. Expected bytes = 0 6. Expected bytes = 0 7. Expected bytes = 0 8. Expected bytes = 0 9. Expected bytes = 0 10. Expected bytes = 0 11. Expected bytes = 0 12. Expected bytes = 0 13. Expected bytes = 0 14. Expected bytes = 0 15. Expected bytes = 0
Edit:
The response code is always 200. [HTTP_OK]
Edit 2:
The first time it takes around 330 ms, the rest take around 220 ms most of the time, but every once in a while the first time is faster. Also, no amount of delay/forcing the gc makes any difference.