我试图使用 Apache AntGet task http://ant.apache.org/manual/Tasks/get.html获取我们公司另一个团队生成的 WSDL 列表。他们将它们托管在 weblogic 9.x 服务器上http://....com:7925/services/ http://....com:7925/services/。我可以通过浏览器访问该页面,但在尝试将页面复制到本地文件进行解析时,获取任务给了我一个 FileNotFoundException 异常。我仍然能够(使用 ant 任务)获取 URL,而无需使用 HTTP 的非标准端口 80。
我查看了 Ant 源代码,并将错误范围缩小到 URLConnection。 URLConnection 似乎无法识别数据是 HTTP 流量,因为它不在标准端口上,即使协议被指定为 HTTP。我使用 WireShark 嗅探流量,并且页面通过网络正确加载,但仍然收到 FileNotFoundException。
在下面的示例中,您将看到错误(为了保护无辜者而更改了 URL)。错误被抛出连接.getInputStream();
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class TestGet {
private static URL source;
public static void main(String[] args) {
doGet();
}
public static void doGet() {
try {
source = new URL("http", "test.com", 7925,
"/services/index.html");
URLConnection connection = source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
对我的 HTTP 请求的响应返回了状态代码 404,这导致当我调用 getInputStream() 时出现 FileNotFoundException。我仍然想阅读响应正文,所以我不得不使用不同的方法:HttpURLConnection#getErrorStream().
下面是 getErrorStream() 的 JavaDoc 片段:
如果满足则返回错误流
连接失败但服务器已发送
尽管如此,有用的数据。典型的
示例是当 HTTP 服务器
响应 404,这会导致
抛出 FileNotFoundException
正在连接,但服务器发送了一个
HTML 帮助页面,包含相关建议
该怎么办。
使用示例:
public static String httpGet(String url) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.connect();
//4xx: client error, 5xx: server error. See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
boolean isError = con.getResponseCode() >= 400;
//In HTTP error cases, HttpURLConnection only gives you the input stream via #getErrorStream().
is = isError ? con.getErrorStream() : con.getInputStream();
String contentEncoding = con.getContentEncoding() != null ? con.getContentEncoding() : "UTF-8";
return IOUtils.toString(is, contentEncoding); //Apache Commons IO
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
//Note: Closing the InputStream manually may be unnecessary, depending on the implementation of HttpURLConnection#disconnect(). Sun/Oracle's implementation does close it for you in said method.
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
if (con != null) {
con.disconnect();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)