SocketException:连接重置

时间:2013-06-11 15:06:00

标签: java sockets

我几乎从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一些权限。我的代码有问题或这是一个环境问题吗?

1 个答案:

答案 0 :(得分:0)

我使用你的代码进行了小修改,因为我手边没有IOUtils。它的工作原理应该如此。无需设置代理。没有特殊权限,因为我是普通用户运行它。

    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();
    }