In my java program,I use URLConnection to get a url.It works fine under windows,but under linux it doesn’t work.And I wanna know why.
codes:
Properties prop = System.getProperties();
prop.setProperty("http.proxyHost", "127.0.0.1");
prop.setProperty("http.proxyPort", "8080");
System.setProperty("sun.net.client.defaultConnectTimeout", "20000");
System.setProperty("sun.net.client.defaultReadTimeout", "20000");
URLConnection conn = new URL(url).openConnection();
InputStream is = conn.getInputStream();
byte [] buff = new byte[is.available()];//1024];
int read = is.read(buff);
System.out.println("buff:" + buff.length);
String result = "";
if(read > 0) {
result = new String(buff, 0, read);
read = is.read(buff);
System.out.println("result:" + result);
}
It turns out that byte is empty and read=0.
But under windows it works fine.
I also tried set the User-Agent field,which makes no different.
HttpURLConnection is also tried,same problem.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
HttpURLConnection conn = (HttpURLConnection)(new URL(url).openConnection(proxy));
This way is tried ,too.Fail either.
All these ways works fine with windows.
The url can be opened fine with firefox on this pc using the same proxy,btw.
In the javadocs for the available() method, it says:
The key is “without blocking”. The method doesn’t return the number of bytes that is expected to be the content length of the url you are trying to read from. Using a fixed sized buffer should solve your problem instead of InputStream.available() which could return 0.