1

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.

Jacob
  • 619
  • 1
  • 5
  • 17
  • Works by Changing `byte [] buff = new byte[is.available()];` to `byte [] buff = new byte[1024];` It seems that `is.available()` doesn't work,but why? – Jacob Mar 09 '12 at 05:47
  • It works all right, it just doesn't do what you seem to think it does. Check the Javadoc. There are few correct uses of `available()`, and this isn't one of them. – user207421 Mar 09 '12 at 06:38

1 Answers1

1

In the javadocs for the available() method, it says:

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

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.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • I figured it out,also see [this](http://stackoverflow.com/questions/5826198/inputstream-available-is-0-always).It only checks if there is data available (in input buffers) in current process.Thanks,pal. – Jacob Mar 09 '12 at 05:58
  • I could guess that the behavior of the underlying OS stream is different, but that's just a guess. There could be a lot of reasons why. – Jon Lin Mar 09 '12 at 06:09