Пример чтения web-стринчки с сервера

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ru.rpod.taop;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.InetAddress;
/**
* User: golodnyj
* Date: 02.03.2009
* Time: 12:27:29
*/
public class ReaderFromWeb {
private static void getDataFromURL(String address) throws Exception {
// Подготовка соединения
URL page = new URL(address);
HttpURLConnection connection = (HttpURLConnection) page.openConnection();
try {
// Открытие подключения
connection.connect();
// Создание входящего потока информации
InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
BufferedReader br = new BufferedReader(in);
StringBuffer sb = new StringBuffer();
// Чтение информации из входящего потока
String line = br.readLine();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
// Отображеине в консоль результатов
System.out.println(sb.toString());
} catch (UnknownHostException e) {
System.out.println("Sorry but the host " + address + " is unknown");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getHostIPByName(String address) {
try {
InetAddress inetAddress = null;
inetAddress = InetAddress.getByName(address);
System.out.println(inetAddress.getHostName() + "="
+ inetAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Sorry but the host " + address + " is unknown");
}
}
public static void main(String[] arguments) throws Exception {
getDataFromURL("http://rpod.ru");
getHostIPByName("rpod.ru");
}
}