jef*_*l8n 23 java ant urlconnection
我试图使用Apache Ant Get任务来获取我们公司中另一个团队生成的WSDL列表.他们将它们托管在http://.... com:7925/services /上的weblogic 9.x服务器上.我能够通过浏览器访问该页面,但是当尝试将页面复制到本地文件进行解析时,get任务会给我一个FileNotFoundException.我仍然能够(使用ant任务)获得没有HTTP的非标准端口80的URL.
我查看了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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
bco*_*ody 46
我的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 19
这是一个旧线程,但我遇到了类似的问题,并找到了一个未在此处列出的解决方案.
我在浏览器中收到的页面很好,但是当我尝试通过HttpURLConnection访问它时得到了404.我尝试访问的URL包含一个端口号.当我尝试没有端口号时,我通过HttpURLConnection成功获得了一个虚拟页面.所以似乎非标准端口是问题所在.
我开始认为访问受到限制,从某种意义上说它是.我的解决方案是我需要告诉服务器User-Agent,我还指定了我期望的文件类型.我正在尝试读取.json文件,所以我认为文件类型也可能是必要的规范.
我添加了这些行,它最终起作用:
httpConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
httpConnection.setRequestProperty("Accept","*/*");
Run Code Online (Sandbox Code Playgroud)