我试图使用Apache 任务来获取我们公司中的另一个团队生成的WSDL列表。他们将它们托管在http://....com:7925/services/上的WebLogic9.x服务器上。我能够通过浏览器到达页面,但是在尝试将页面复制到本地文件以进行解析时,get任务会给我一个FileNotFoundException。我仍然能够(使用ant任务)获得一个URL,而不需要HTTP的非标准端口80。
我查看了Ant源代码,并将错误缩小到URLConnection。似乎URLConnection不承认数据是HTTP流量,因为它不在标准端口上,即使协议被指定为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());
}
}
}发布于 2009-06-03 03:19:51
检查服务器返回的响应代码。
发布于 2010-11-09 18:07:37
对我的HTTP请求的响应以状态代码404返回,这将在我调用getInputStream()时生成一个getInputStream。我仍然想阅读响应体,所以我不得不使用另一种方法:HttpURLConnection#getErrorStream().
下面是JavaDoc的getErrorStream()片段:
如果连接失败,但服务器仍然发送有用的数据,则返回错误流。典型的例子是当HTTP服务器使用404进行响应时,这将导致在connect中抛出一个FileNotFoundException,但是服务器发送了一个help,并给出了有关应该做什么的建议。
用法示例:
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();
}
}
}发布于 2010-02-16 16:42:42
这是一个旧线程,但我也遇到了类似的问题,并找到了一个不在这里列出的解决方案。
我在浏览器中收到页面罚款,但当我试图通过HttpURLConnection访问它时,得到了404。我试图访问的URL包含一个端口号。当我尝试没有端口号时,我成功地通过HttpURLConnection获得了一个虚拟页面。所以似乎非标准港口才是问题所在。
我开始认为进入是受到限制的,从某种意义上说是这样的。我的解决方案是,我需要告诉服务器用户-代理,我还指定了我期望的文件类型。我正在尝试读取一个.json文件,所以我认为文件类型也可能是一个必要的规范。
我添加了这些行,它终于起作用了:
httpConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
httpConnection.setRequestProperty("Accept","*/*");https://stackoverflow.com/questions/941628
复制相似问题