在我的java程序中,我使用URLConnection来获取url.It在windows下工作正常,但在linux下它不起作用。我想知道原因。
代码:
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);
}
事实证明,byte是空的,read = 0。
但是在Windows下它运行正常。
我也尝试过设置User-Agent字段,这没什么不同。
也尝试了HttpURLConnection,同样的问题。
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
HttpURLConnection conn = (HttpURLConnection)(new URL(url).openConnection(proxy));
也尝试了这种方式。失败。
所有这些方法都适用于Windows。
使用相同的代理,btw。
可以在这台电脑上使用firefox打开网址答案 0 :(得分:1)
在available()方法的javadoc中,它说:
返回下一次调用此输入流的方法时,从此输入流无阻塞读取(或跳过)的字节数估计值。
关键是“无阻塞”。该方法不返回预期为您尝试读取的URL的内容长度的字节数。使用固定大小的缓冲区应该解决您的问题,而不是可能返回0的InputStream.available()。