public class HttpPageFetch extends TestCase {
//最简单的获取网页内容的示例
@Test
public void testFetch01() {
try {
String urlString = "http://empower.edtest.com:8080/";
URL url = new URL(urlString); // 代表了一个网址
InputStream is = url.openStream(); // 获得网页的内容
// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上述例子太过简单,假如你需要通过代理来访问网络,那么,你需要的是URLConnection!即,在获取内容之前,先设置代理!
*/
public void testFetch02() {
try {
String urlString = "http://www.ibm.com/developerworks/cn/java/j-javaroundtable/index.html";
URL url = new URL(urlString); // 代表了一个网址
// 首先创建HTTP代理,指定代理的地址和端口
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
"79.120.193.53", 80));
/**
* 首先打开一个连接对象 可以通过这个对象,在真正发起请求之前,设置一些其它的信息 比如:代理服务器等
*/
URLConnection conn = url.openConnection(proxy);
InputStream is = conn.getInputStream(); // 获得网页的内容
// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* HttpURLConnection 是URLConnection 的子类,它提供了更多与HTTP 有关的处理方法,
* 比如:如果你希望获得服务器响应的HTTP代码,比如:2XX,3XX等 比如:你希望设置是否自动进行客户端重定向(缺省是自动重定向)
* 比如:你希望指定向服务器提交的 HTTP METHOD(GET 或POST 等)
*/
public void testFetch03() {
try {
String urlString = "http://localhost:8080/cms/backend/main.jsp";
URL url = new URL(urlString); // 代表了一个网址
// 设置是否自动进行重定向,缺省这个值为true
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置HTTP METHOD
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
System.out.println("服务器响应代码为:" + code);
InputStream is = conn.getInputStream();
// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文参考:李腾飞学习笔记HttpClient 入门。