我在服务器上存储了一个 html 文件。我有这样的 URL 路径:<https://localhost:9443/genesis/Receipt/Receipt.html >
我想从 url 中读取包含标签的 html 文件的内容,即 html 文件的源代码。
我该怎么做?这是一个服务器端代码,不能有浏览器对象,我不确定使用 URLConnection 是否是一个不错的选择。
现在最好的解决方案应该是什么?
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 URLContent {
public static void main(String[] args) {
try {
// get URL content
String a = "http://localhost:8080//TestWeb/index.jsp";
URL url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用spring解决了它,将bean添加到spring配置文件中
<bean id = "receiptTemplate" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="/WEB-INF/Receipt/Receipt.html"></constructor-arg>
</bean>
然后用我的方法阅读
// read the file into a resource
ClassPathResource fileResource =
(ClassPathResource)context.getApplicationContext().getBean("receiptTemplate");
BufferedReader br = new BufferedReader(new FileReader(fileResource.getFile()));
String line;
StringBuffer sb =
new StringBuffer();
// read contents line by line and store in the string
while ((line =
br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
举个例子 :
URL url = new URL("https://localhost:9443/genesis/Receipt/Receipt.html");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String l;
while ((l=in.readLine())!=null) {
System.out.println(l);
}
您可以以其他方式使用输入流,而不仅仅是打印它。
当然如果你有本地文件的路径,你也可以这样做
InputStream in = new FileInputStream(new File(yourPath));
import java.net.*;
import java.io.*;
//...
URL url = new URL("https://localhost:9443/genesis/Receipt/Receipt.html");
url.openConnection();
InputStream reader = url.openStream();
我认为最简单的方法是使用IOUtils
import com.amazonaws.util.IOUtils;
...
String uri = "https://localhost:9443/genesis/Receipt/Receipt.html";
String fileContents = IOUtils.toString(new URL(uri).openStream());
System.out.println(fileContents);