[英]Java URLConnection works with windows,but not with linux
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. 在我的Java程序中,我使用URLConnection来获取一个url。它在Windows下可以正常工作,但是在Linux下却无法工作。我想知道为什么。
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. 事实证明,该字节为空并且读取= 0。
But under windows it works fine. 但是在Windows下它可以正常工作。
I also tried set the User-Agent field,which makes no different. 我也尝试设置User-Agent字段,这没有什么不同。
HttpURLConnection is also tried,same problem. HttpURLConnection也尝试过,同样的问题。
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. 所有这些方式在Windows下都可以正常工作。
The url can be opened fine with firefox on this pc using the same proxy,btw. 可以使用同一代理btw在此PC上使用Firefox很好地打开url。
In the javadocs for the available() method, it says: 在available()方法的javadocs中,它表示:
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. 该方法不会返回预期为您尝试读取的url内容长度的字节数。 Using a fixed sized buffer should solve your problem instead of InputStream.available() which could return 0. 使用固定大小的缓冲区应该可以解决您的问题,而不是可以返回0的InputStream.available()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.