Java 给定的URL具有fileNotFoundException

Java 给定的URL具有fileNotFoundException,java,url,stream,filenotfoundexception,Java,Url,Stream,Filenotfoundexception,我有下面的代码,它在我的本地开发服务器上运行完全正常,但是当我上传到部署服务器时,我总是点击file not found Exception String urlStr = "http://" + getContext().getRequest().getServerName() + getContext().getServletContext().getContextPath() + "test.action"; URL url = new URL(urlStr); InputStream i

我有下面的代码,它在我的本地开发服务器上运行完全正常,但是当我上传到部署服务器时,我总是点击file not found Exception

String urlStr = "http://" + getContext().getRequest().getServerName() +
getContext().getServletContext().getContextPath() + "test.action";
URL url = new URL(urlStr);
InputStream input = url.openStream(); //Error always occurs here, it gives me the correct URL but it says file not found.

有人能帮我吗?

因为这是一个HTTP URL。正确的方法如下

String urlStr = "http://" + getContext().getRequest().getServerName() +
        getContext().getServletContext().getContextPath() + "test.action";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) { 
    InputStream input = conn.getInputStream();
}

我认为@deadlock的评论可能是解决这个问题的关键

您将收到FileNotFoundException,因为远程服务器正在发送404 Not Found响应。最可能的解释是,您试图使用错误的URL进行连接。在尝试连接之前,请打印出URL字符串

所有证据都表明服务器正在发送404未找到响应。。。对于两个版本的代码。这通常意味着你的URL是错误的。但也有可能是其他事情:

您可能在Java和浏览器案例中使用不同的代理,导致Java案例到达一些不理解URL的服务器

可以想象,服务器正在实施一些反网络抓取机制,并向您发送404响应,因为这正确地认为您的请求不是来自web浏览器


您的应用程序服务器的名称?抱歉,这是一个输入错误。应用程序服务器是EatJ server。为什么不打印urlStr以查看其中的内容?我尝试过,这是一个正确的URL,我使用该URL将其粘贴到我的浏览器上,它可以工作。是的。。。我想不会的。conn.getResponseCode给了你什么值?404表示找不到。大家好,谢谢你们的帮助,我不知道为什么它不起作用,但我已经在后端逻辑中呈现了HTML。我尝试过了,它是一个正确的URL,我将相同的URL粘贴到浏览器中,它会返回一个结果。