我有一個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」);' –