我有一个html文件存储在服务器上。我有这样的URL路径:<https://localhost:9443/genesis/Receipt/Receipt.html >
如何获取url html内容到java中的字符串
我想从网址即html文件的源代码中读取此html文件的内容,该文件将包含标签。
我该怎么做?这是一个服务器端代码,不能有浏览器对象,我不确定使用URLConnection会是一个不错的选择。
现在最好的解决方案是什么?
我有一个html文件存储在服务器上。我有这样的URL路径:<https://localhost:9443/genesis/Receipt/Receipt.html >
如何获取url html内容到java中的字符串
我想从网址即html文件的源代码中读取此html文件的内容,该文件将包含标签。
我该怎么做?这是一个服务器端代码,不能有浏览器对象,我不确定使用URLConnection会是一个不错的选择。
现在最好的解决方案是什么?
使用它春天 加豆到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的其他方式,而不仅仅是打印。
当然,如果你有路径到本地文件,你也可以做
InputStream in = new FileInputStream(new File(yourPath));
this是一个服务器端代码,我不想使用URLConnection。不知道这是否是一个好方法。你怎么看? –
这不是服务器端代码,为什么你不使用URLConnection? –
如果你知道你的文件在本地,你也可以使用'FileInputStream'(见扩展答案)。 –
import java.net.*;
import java.io.*;
//...
URL url = new URL("https://localhost:9443/genesis/Receipt/Receipt.html");
url.openConnection();
InputStream reader = url.openStream();
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 URLConetent{
public static void main(String[] args) {
URL url;
try {
// get URL content
String a="http://localhost:8080//TestWeb/index.jsp";
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();
}
}
}
如何在远程站点的网址?问题实际上在脚本位置 – NPE
'String content = org.apache.commons.io.IOUtils.toString(new Url(“https:// localhost:9443/genesis/Receipt/Receipt.html”),“utf8”);' –