Java读取URL到字符串
时间:2020-02-23 14:36:48 来源:igfitidea点击:
在当前项目中,我需要从URL读取WSDL文件并将其作为CLOB存储到数据库中。
不需要验证,因此它是将URL内容读取到String,然后将其存储到数据库表中。
Java读取URL到字符串
这是我用Java编写的用于读取URL到String的程序。
package com.theitroad.java;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class ReadURLToString {
public static void main(String[] args) throws Exception {
URL test = new URL("https://theitroad.local");
URLConnection uc = test.openConnection();
uc.addRequestProperty("User-Agent", "Mozilla/4.0");
BufferedReader in = new BufferedReader(new InputStreamReader(uc
.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
System.out.println(inputLine);
}
in.close();
System.out.println("HTML Data:" + sb.toString());
}
}
当我们运行上面的程序时,它将产生以下输出。
除了设置HTTP用户代理外,大多数代码都是易于理解的。
对于某些,如果您未设置" User-Agent"标头,则可能会收到403错误代码。
这是因为他们具有网络服务器安全性,可避免漫游器流量。
如果从上述程序中删除User-Agent的设置,将产生以下错误。
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.theitroad.local/ at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) at ReadURLToString.main(ReadURLToString.java:12)

