2014-02-06 36 views
0

我正在编写一个将请求发送到服务器的客户端应用程序。我使用StartServer批处理文件从Windows启动了我的服务器。现在,服务器期望的请求是HTTP请求。如果我从我的Web浏览器打开一个请求,服务器就会看到它并对它作出响应,但是我尝试从Java发送请求时遇到了困难。url.openStream上的FileNotFound()

例如,命令"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例外。对此有何建议?

回答

0

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

+0

是的,它与127.0.0.1一样 – Whizzil

0

您是否尝试过以不同方式访问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地址,而不是本地主机是一个好主意,因为在另一个答案建议。

+0

仍然是相同的问题,线程“main”中的异常java.io.FileNotFoundException:http://127.0.0.1/?command=reg&person=sophie – Whizzil

+0

也许添加端口号码到URL将有所帮助 – ltalhouarne

+0

添加端口没有帮助,它是众所周知的门80,无论如何。 – Whizzil