【问题标题】:FileNotFound on url.openStream()url.openStream() 上的 FileNotFound
【发布时间】:2014-03-03 23:27:09
【问题描述】:

我正在编写一个向服务器发送请求的客户端应用程序。我已经使用 StartServer 批处理文件从 Windows 启动了我的服务器。现在,服务器期望的请求是 HTTP 请求。如果我从 Web 浏览器打开请求,服务器会看到并响应它,但我在尝试从 Java 发送请求时遇到了麻烦。

例如,命令"http://localhost/?command=reg&person=sophie" 从浏览器启动时工作正常,但从 Java 中返回 FileNotFound 异常。

代码如下:

public class Client {

private Socket clientSocket;
private final int PORT_NUMBER;
private final String HOST_NAME;

private PrintWriter writer;
private BufferedReader reader;

public Client(int PORT_NUMBER, String HOST_NAME){
    this.PORT_NUMBER = PORT_NUMBER;
    this.HOST_NAME = HOST_NAME;


    try {
        clientSocket = new Socket(HOST_NAME, PORT_NUMBER);
        writer = new PrintWriter(clientSocket.getOutputStream(), true);
        reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("Error creating socket!");
    }
}


public void registerPerson(String personName) throws IOException{

    URL url = new URL("http://localhost/?command=reg&person=sophie");
    InputStream in = new BufferedInputStream(url.openStream());
    Scanner sc = new Scanner(in);
    sc.nextLine();

}

InputStream in = new BufferedInputStream(url.openStream()); 这一行返回一个 FileNotFound 异常。对此有何建议?

【问题讨论】:

    标签: java sockets url


    【解决方案1】:

    您是否尝试过使用 127.0.0.1 而不是 localhost。这个问题可能是因为java无法识别你的环回地址(即localhost)。

    【讨论】:

    • 是的,127.0.0.1都一样
    【解决方案2】:

    您是否尝试过以不同方式访问 URL?

          URL fileURL = new URL("http://localhost/?command=reg&person=sophie");
          URLConnection connection = fileURL.openConnection();
          connection.connect();
          inputStream = new java.io.BufferedInputStream(connection.getInputStream());
    

    正如另一个答案中所建议的那样,使用 IP 地址而不是 localhost 也是一个好主意。

    【讨论】:

    • 还是同样的问题,线程“main”java.io.FileNotFoundException中的异常:127.0.0.1/?command=reg&person=sophie
    • 或许将端口号添加到 URL 会有所帮助
    • 添加端口没有帮助,反正它是众所周知的 80 号门。
    猜你喜欢
    • 2012-06-15
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2014-01-16
    • 1970-01-01
    • 2016-01-23
    • 2018-04-16
    相关资源
    最近更新 更多