java - 如何修复 'java.io.FileNotFoundException: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 (Unknown Source)'错误?

标签 java jnlp

我正在尝试将小程序转换为 Java 应用程序。因此,我生成了 JNLP 文件并传递了 POST 方法所需的所有参数。 当我从 JNLP 启动应用程序时,我收到此错误:

java.io.FileNotFoundException: http://PATH_TO_A_DIRECTORY/reopen.php
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.access$200(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$9.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$9.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessController.doPrivilegedWithCombiner(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at maarchcm.MaarchCM.sendHttpRequest(MaarchCM.java:368)
    at maarchcm.MaarchCM.editObject(MaarchCM.java:261)
    at maarchcm.MaarchCM.test(MaarchCM.java:106)
    at maarchcm.MaarchCM.main(MaarchCM.java:188)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javaws.Launcher.executeApplication(Unknown Source)
    at com.sun.javaws.Launcher.executeMainClass(Unknown Source)
    at com.sun.javaws.Launcher.doLaunchApp(Unknown Source)
    at com.sun.javaws.Launcher.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

异常说文件“reopen.php”丢失,但异常中提到的路径是错误的,我没有在代码中调用它。 当我将其作为小程序启动时,效果很好,但不能作为应用程序启动。 我真的不知道代码中可能存在什么错误。 这是我的代码。

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import netscape.javascript.JSException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import netscape.javascript.JSObject;

public class MaarchCM extends JApplet {
    //INIT PARAMETERS
    protected String url;
    protected String objectType;
    protected String objectTable;
    protected String objectId;
    protected String userLocalDirTmp;
    protected String userMaarch;
    protected String userMaarchPwd;
    protected String psExecMode;

    protected String messageStatus;

    Hashtable app = new Hashtable();
    Hashtable messageResult = new Hashtable();

    //XML PARAMETERS
    protected String status;
    protected String appPath;
    protected String fileContent;
    protected String fileExtension;
    protected String error;
    protected String endMessage;
    protected String os;

    protected String fileContentTosend;

    public myLogger logger;

    public void init() throws JSException
    {
        System.out.println("----------BEGIN PARAMETERS----------");
        this.url = this.getParameter("url");
        this.objectType = this.getParameter("objectType");
        this.objectTable = this.getParameter("objectTable");
        this.objectId = this.getParameter("objectId");
        this.userMaarch = this.getParameter("userMaarch");
        this.userMaarchPwd = this.getParameter("userMaarchPwd");
        this.psExecMode = this.getParameter("psExecMode");

        System.out.println("URL : " + this.url);
        System.out.println("OBJECT TYPE : " + this.objectType);
        System.out.println("OBJECT TABLE : " + this.objectTable);
        System.out.println("OBJECT ID : " + this.objectId);
        System.out.println("USER MAARCH : " + this.userMaarch);
        System.out.println("PSEXEC MODE : " + this.psExecMode);

        System.out.println("----------END PARAMETERS----------");
        try {
            this.editObject();
            this.destroy();
            this.stop();
            System.exit(0);
        } catch (Exception ex) {
            Logger.getLogger(MaarchCM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void test(String[] args)
    {
        System.out.println("----------TESTS----------");
        System.out.println("----------BEGIN PARAMETERS----------");
        this.url = args[0];
        this.objectType = args[1];
        this.objectTable = args[2];
        this.objectId = args[3];
        this.userMaarch = args[4];
        this.userMaarchPwd = args[5];
        this.psExecMode = args[6];

        System.out.println("URL : " + this.url);
        System.out.println("OBJECT TYPE : " + this.objectType);
        System.out.println("OBJECT TABLE : " + this.objectTable);
        System.out.println("OBJECT ID : " + this.objectId);
        System.out.println("USER MAARCH : " + this.userMaarch);
        System.out.println("USER MAARCHPWD : " + this.userMaarchPwd);
        System.out.println("PSEXEC MODE : " + this.psExecMode);

        System.out.println("----------END PARAMETERS----------");
        try {
            this.editObject();
        } catch (Exception ex) {
            Logger.getLogger(MaarchCM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void parse_xml(InputStream flux_xml) throws SAXException, IOException, ParserConfigurationException
    {
        this.logger.log("----------BEGIN PARSE XML----------", Level.INFO);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(flux_xml);
        this.messageResult.clear();
        NodeList level_one_list = doc.getChildNodes();
        for (Integer i=0; i < level_one_list.getLength(); i++) {
            NodeList level_two_list = level_one_list.item(i).getChildNodes();
            if ("SUCCESS".equals(level_one_list.item(i).getNodeName())) {
                for(Integer j=0; j < level_one_list.item(i).getChildNodes().getLength(); j++ ) {
                    this.messageResult.put(level_two_list.item(j).getNodeName(),level_two_list.item(j).getTextContent());
                }
                this.messageStatus = "SUCCESS";
            } else if ("ERROR".equals(level_one_list.item(i).getNodeName()) ) {
                for(Integer j=0; j < level_one_list.item(i).getChildNodes().getLength(); j++ ) {
                    this.messageResult.put(level_two_list.item(j).getNodeName(),level_two_list.item(j).getTextContent());
                }
                this.messageStatus = "ERROR";
            }
        }
        this.logger.log("----------END PARSE XML----------", Level.INFO);
    }

    public void processReturn(Hashtable result) {
        Iterator itValue = result.values().iterator(); 
        Iterator itKey = result.keySet().iterator();
        while(itValue.hasNext()) {
            String value = (String)itValue.next();
            String key = (String)itKey.next();
            this.logger.log(key + " : " + value, Level.INFO);
            if ("STATUS".equals(key)) {
                this.status = value;
            }
            if ("OBJECT_TYPE".equals(key)) {
                this.objectType = value;
            }
            if ("OBJECT_TABLE".equals(key)) {
                this.objectTable = value;
            }
            if ("OBJECT_ID".equals(key)) {
                this.objectId = value;
            }
            if ("APP_PATH".equals(key)) {
                //this.appPath = value;
            }
            if ("FILE_CONTENT".equals(key)) {
                this.fileContent = value;
            }
            if ("FILE_EXTENSION".equals(key)) {
                this.fileExtension = value;
            }
            if ("ERROR".equals(key)) {
                this.error = value;
            }
            if ("END_MESSAGE".equals(key)) {
                this.endMessage = value;
            }
        }
        //send message error to Maarch if necessary
        if (!this.error.isEmpty()) {
            this.sendJsMessage(this.error.toString());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try{
            System.out.println(args[0]);
            System.out.println(args[1]);
            System.out.println(args[2]);
            System.out.println(args[3]);
            System.out.println(args[4]);
            MaarchCM maarchCM = new MaarchCM();
            maarchCM.test(args);
        }
       catch(Exception e) {
           String exMessage = e.toString();
           System.out.println(exMessage);
       }
    }

    public String editObject() throws Exception, InterruptedException, JSException {
        System.out.println("----------BEGIN EDIT OBJECT----------");
        System.out.println("----------BEGIN LOCAL DIR TMP IF NOT EXISTS----------");
        String os = System.getProperty("os.name").toLowerCase();
        boolean isUnix = os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0;
        boolean isWindows = os.indexOf("win") >= 0;
        boolean isMac = os.indexOf("mac") >= 0;
        this.userLocalDirTmp = System.getProperty("user.home");
        //this.userLocalDirTmp = "C:/repertoire avec espaces";
        //this.userLocalDirTmp = "c:\\maarch";
        //this.userLocalDirTmp = "\\\\192.168.21.100\\Public\\montage_nas\\avec espaces";

        fileManager fM = new fileManager();
        fM.createUserLocalDirTmp(this.userLocalDirTmp);
        if (isWindows) {
            System.out.println("This is Windows");
            this.userLocalDirTmp = this.userLocalDirTmp + "\\maarchTmp\\";
            //this.appPath = this.userLocalDirTmp.replaceAll(" ", "%20") + "start.bat";
            //this.appPath = "\""+this.userLocalDirTmp + "start.bat\"";
            this.appPath = this.userLocalDirTmp + "start.bat";
            this.os = "win";
        } else if (isMac) {
            System.out.println("This is Mac");
            this.userLocalDirTmp = this.userLocalDirTmp + "/maarchTmp/";
            this.appPath = this.userLocalDirTmp + "start.sh";
            this.os = "mac";
        } else if (isUnix) {
            System.out.println("This is Unix or Linux");
            this.userLocalDirTmp = this.userLocalDirTmp + "/maarchTmp/";
            this.appPath = this.userLocalDirTmp + "start.sh";
            this.os = "linux";
        } else {
            System.out.println("Your OS is not supported!!");
        }
        System.out.println("APP PATH: " + this.appPath);
        System.out.println("----------BEGIN LOCAL DIR TMP IF NOT EXISTS----------");

        fM.createUserLocalDirTmp(this.userLocalDirTmp);
        System.out.println("----------END LOCAL DIR TMP IF NOT EXISTS----------");

        System.out.println("Create the logger");
        this.logger = new myLogger(this.userLocalDirTmp);

        if (this.psExecMode.equals("OK")) {
            this.logger.log("----------BEGIN PSEXEC MODE----------", Level.INFO);
            boolean isPsExecExists = fM.isPsExecFileExists(this.userLocalDirTmp + "PsExec.exe");
            if (!isPsExecExists) {
                this.logger.log("----------BEGIN TRANSFER OF PSEXEC----------", Level.INFO);
                String urlToSend = this.url + "?action=sendPsExec&objectType=" + this.objectType
                        + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
                sendHttpRequest(urlToSend, "none");
                this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
                this.logger.log("MESSAGE RESULT : ", Level.INFO);
                this.processReturn(this.messageResult);
                this.logger.log("CREATE THE FILE : " + this.userLocalDirTmp + "PsExec.exe", Level.INFO);
                fM.createFile(this.fileContent, this.userLocalDirTmp + "PsExec.exe");
                this.fileContent = "";
                this.logger.log("----------END TRANSFER OF PSEXEC----------", Level.INFO);
            }
            this.logger.log("----------END PSEXEC MODE----------", Level.INFO);
        }

        this.logger.log("----------BEGIN OPEN REQUEST----------", Level.INFO);
        String urlToSend = this.url + "?action=editObject&objectType=" + this.objectType
                        + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
        sendHttpRequest(urlToSend, "none");
        this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
        this.logger.log("MESSAGE RESULT : ", Level.INFO);
        this.processReturn(this.messageResult);
        this.logger.log("----------END OPEN REQUEST----------", Level.INFO);

        String fileToEdit = "thefile." + this.fileExtension;

        this.logger.log("----------BEGIN CREATE THE BAT TO LAUNCH IF NECESSARY----------", Level.INFO);
        this.logger.log("create the file : "  + this.appPath, Level.INFO);
        fM.createBatFile(
            this.appPath, 
            this.userLocalDirTmp, 
            fileToEdit, 
            this.os,
            this.userMaarch,
            this.userMaarchPwd,
            this.psExecMode,
            this.userLocalDirTmp
        );
        this.logger.log("----------END CREATE THE BAT TO LAUNCH IF NECESSARY----------", Level.INFO);

        if ("ok".equals(this.status)) {
            this.logger.log("RESPONSE OK", Level.INFO);

            this.logger.log("----------BEGIN EXECUTION OF THE EDITOR----------", Level.INFO);
            this.logger.log("CREATE FILE IN LOCAL PATH", Level.INFO);
            fM.createFile(this.fileContent, this.userLocalDirTmp + fileToEdit);

            //this.logger.log("CREATE FILE TO CHANGE RIGHTS IN THE TMP DIR", Level.INFO);
            //fM.createRightsFile(this.userLocalDirTmp, this.userMaarch);

            /*this.logger.log("LAUNCH VBS TO CHANGE RIGHTS IN THE TMP DIR", Level.INFO);
            final String vbsPath = this.userLocalDirTmp + "setRights.vbs";
            Process procVbs = fM.launchApp("cmd /c wscript //B " + vbsPath);
            procVbs.waitFor();*/

            final String exec;

            this.logger.log("LAUNCH THE EDITOR !", Level.INFO);
            if (isUnix) {
                exec = this.appPath;
            }else{
               exec = "\""+this.appPath+"\""; 
            }

            this.logger.log("EXEC PATH : " + exec, Level.INFO);
            Process proc = fM.launchApp(exec);
            proc.waitFor();

            this.logger.log("----------END EXECUTION OF THE EDITOR----------", Level.INFO);

            this.logger.log("----------BEGIN RETRIEVE CONTENT OF THE OBJECT----------", Level.INFO);
            this.fileContentTosend = fM.encodeFile(this.userLocalDirTmp + "thefile." + this.fileExtension);
            this.logger.log("----------END RETRIEVE CONTENT OF THE OBJECT----------", Level.INFO);

            String urlToSave = this.url + "?action=saveObject&objectType=" + this.objectType 
                            + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
            this.logger.log("----------BEGIN SEND OF THE OBJECT----------", Level.INFO);
            this.logger.log("URL TO SAVE : " + urlToSave, Level.INFO);
            sendHttpRequest(urlToSave, this.fileContentTosend);
            this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
            this.logger.log("LAST MESSAGE RESULT : ", Level.INFO);
            this.processReturn(this.messageResult);
            //send message to Maarch at the end
            if (!this.endMessage.isEmpty()) {
                this.sendJsMessage(this.endMessage.toString());
            }
            this.sendJsEnd();
            this.logger.log("----------END SEND OF THE OBJECT----------", Level.INFO);
        } else {
            this.logger.log("RESPONSE KO", Level.WARNING);
        }
        this.logger.log("----------END EDIT OBJECT----------", Level.INFO);
        return "ok";
    }

    public void sendJsMessage(String message) throws JSException
    {
        JSObject jso;
        jso = JSObject.getWindow(this);
        this.logger.log("----------JS CALL sendAppletMsg TO MAARCH----------", Level.INFO);
        jso.call("sendAppletMsg", new String[] {String.valueOf(message)});
    }

    public void sendJsEnd() throws InterruptedException, JSException
    {
        JSObject jso;
        jso = JSObject.getWindow(this);
        this.logger.log("----------JS CALL endOfApplet TO MAARCH----------", Level.INFO);
        jso.call("endOfApplet", new String[] {String.valueOf(this.objectType), this.endMessage});    
    }

    public void sendHttpRequest(String theUrl, String postRequest) throws Exception {
        URL UrlOpenRequest = new URL(theUrl);
        HttpURLConnection HttpOpenRequest = (HttpURLConnection) UrlOpenRequest.openConnection();
        HttpOpenRequest.setDoOutput(true);
        HttpOpenRequest.setRequestMethod("POST");
        if (!"none".equals(postRequest)) {
            OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream());
            writer.write("fileContent=" + this.fileContentTosend + "&fileExtension=" + this.fileExtension);
            writer.flush();
        } else {
            OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream());
            writer.write("foo=bar");
            writer.flush();
        }
        int statusCode = HttpOpenRequest.getResponseCode();
        System.out.println("Coooode: "+statusCode); 
        this.parse_xml(HttpOpenRequest.getInputStream());
        HttpOpenRequest.disconnect();
    }
}

最佳答案

当服务器响应为“404 Not Found”或“410 Gone”时,您将从 HttpURLConnection.getInputStream 收到 FileNotFoundException。 (任何其他问题都会给您带来不同的异常(exception)。)

那么为什么你会得到 404 或 410 呢?

404 最可能的解释是 URL 不正确。也可能是您的 HTTP 代理配置有问题,或者您正在通信的 Web 服务器本身配置错误或损坏,或者...不恰本地发送 404 响应1

(我假设 http://PATH_TO_A_DIRECTORY/reopen.php 不是真正的 URL。)

仅当 URL 正确时才可能出现 410,但它指的是过去存在但已被删除的资源。 (IMO)您极不可能遇到这种情况。


The exception says that the file "reopen.php" is missing, but the path mentioned in the exception is wrong, and I don't call it in my code.

如果服务器发送 3xx 重定向,则异常中的 url 可能与您提供的 url 不同。因此,我怀疑问题在于服务器正在重定向到不存在的资源的 URL。这是服务器错误!

您可以通过调试或阅读源代码来确认这一点2

      sun.net.www.protocol.http.HttpURLConnection

或者您可以使用网络浏览器的开发工具检查重定向行为。


1 - 一些网络开发人员通过无知、懒惰......或试图误导网络抓取工具,对网站进行编码以发送不适当的响应代码。
2 - 要查找 OpenJDK 类的源代码,请在 google 中搜索“ 源代码”。或者,您可以从 https://openjdk.java.net/ 下载或查看源代码

关于java - 如何修复 'java.io.FileNotFoundException: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 (Unknown Source)'错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56704450/

相关文章:

java - 与 Java 并行创建对象

java - JSONObject 文本必须以 '{' 错误开头

java - 如何升级Tomcat Java Applet以使用JNLP?

java - 如何使用内存数据库编写测试用例?

Java打开文件错误: can't find the specified path

java - 运行重复的 JavaWS 应用程序

java - 使用 jnlp/webstart 在 OSX 上使用 Java 7 对文件名进行编码问题

java - 使用 GAE servlet 为 JavaWS 提供动态 JNLP 和 jar

java - 如何使用 Java Webstart 应用程序管理证书更新

java - 最终类是否必须重写 equals() 和 hashCode() 方法