一、Java中调用servlet说明:
我们有时可能需要在Java类中调用Servlet从而实现某些特殊的功能,在JavaAPI中提供了一个URL的类,其中openStream( )方法可以打开URL的连接,并返回一个用于该连接读入的InputStream。
二、Java中调用servlet应用举例:
package com.solid.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class TestCallServlet {
//servlet路径
private static final String path = "http://localhost:8080/test/servlet/TestServlet";
/**
* 测试调用servlet方法
* @param args
*/
public static void main(String[] args) {
try {
URL url = new URL(path);
url.openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、读取某个页面源代码的应用举例:
package com.solid.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class TestReaderSource {
//URL路径
private static final String path = "http://www.google.cn";
//读取path路径下页面的源代码方法测试
public static void main(String[] args) {
BufferedReader br = null;
String source;
try {
URL url = new URL(path);
URLConnection conn = url.openConnection();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((source=br.readLine())!=null) {
System.out.println(source);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}