我几乎从here复制了以下代码。我在第10行收到一个java.net.SocketException,上面写着“连接重置”。
import java.net.*;
import java.io.*;
import org.apache.commons.io.*;
public class HelloWorld {
public static void main(String[] x) {
try {
URL url = new URL("http://money.cnn.com/2013/06/07/technology/security/page-zuckerberg-spying/index.html");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.print(body);
} catch (Exception e) {
e.printStackTrace();
}
}
}我担心这实际上可能不是实际代码的问题,而是我需要授予Java的一些权限。我的代码有问题吗?或者这是环境问题?
发布于 2013-06-11 23:47:17
我使用你的代码做了很小的修改,因为我手头没有IOUtils。它的工作方式应该是这样的。不需要设置agent。也没有特殊的特权,因为我运行它的普通用户。
try {
URL url = new URL("http://money.cnn.com/2013/06/07/technology/security/page-zuckerberg-spying/index.html");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
System.out.print(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}https://stackoverflow.com/questions/17047479
复制相似问题