如何使用java套接字编程获取网站(单个文本文件)的内容

时间:2013-11-05 16:25:58

标签: java sockets network-programming

Socket sock = new Socket(HOST, 80);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
writer.write("GET "+"......txt "+"HTTP/1.1\r\n"
            + "Host: HOST\r\n"
            + "Connection: keep-alive\r\n"
            + "\r\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));

String serverMsg = reader.readLine();
String line = "";
while((line = reader.readLine()) != null)
    System.out.println("answer: " + serverMsg);

2 个答案:

答案 0 :(得分:0)

当然使用套接字是可行的,使用URL(和URLConnection)代替它会更方便:

URL url = new URL("http://url.of.your.webpage");
try (InputStream is = url.openStream()) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line = reader.readLine();
    while (line != null) {
        System.out.println(line);
        line = reader.readLine();
    }
}

此示例仅使用URL#openStream()。如果您需要更多控制连接,请改用URL#openConnection()

URL url = new URL("http://url.of.your.webpage");
URLConnection connection = url.openConnection();
// configure connection
connection.connect();
try (InputStream is = connection.getInputStream()) {
    // ...
}

答案 1 :(得分:0)

只是猜测,因为你的问题很不清楚,但尝试改变:

while((line = reader.readLine()) != null)
    System.out.println("answer: " + serverMsg);

while((line = reader.readLine()) != null)
    System.out.println("answer: " + line);

在您发布的代码中,您继续分配到line,但实际上并未将其打印出来。