gpt4 book ai didi

java - 非标准 HTTP 端口源的 URLConnection FileNotFoundException

转载 作者:IT老高 更新时间:2023-10-28 20:30:41 29 4
gpt4 key购买 nike

我尝试使用 Apache Ant Get task获取我们公司另一个团队生成的 WSDL 列表。他们将它们托管在 http://....com:7925/services/ 上的 weblogic 9.x 服务器上。 .我可以通过浏览器访问该页面,但是当尝试将页面复制到本地文件进行解析时,get 任务给了我一个 FileNotFoundException。我仍然能够(使用 ant 任务)获得一个没有用于 HTTP 的非标准端口 80 的 URL。

我查看了 Ant 源代码,并将错误缩小到 URLConnection。似乎 URLConnection 无法识别数据是 HTTP 流量,因为它不在标准端口上,即使协议(protocol)被指定为 HTTP。我使用 WireShark 嗅探了流量,页面通过网络正确加载,但仍然收到 FileNotFoundException。

这是一个您将看到错误的示例(更改了 URL 以保护无辜者)。 connection.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 片段:

Returns the error stream if the connection failed but the server sent useful data nonetheless. The typical example is when an HTTP server responds with a 404, which will cause a FileNotFoundException to be thrown in connect, but the server sent an HTML help page with suggestions as to what to do.

使用示例:

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();
}
}
}

关于java - 非标准 HTTP 端口源的 URLConnection FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/941628/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com