我正在尝试Java applet,并在Servlet和applet之间进行通信。我要从URLConnection对象检索输入流时遇到HTTP 501错误。

我知道501错误意味着我正在尝试执行未配置连接的操作(在我的情况下为GET操作),但是我认为下面的代码确实接受输入,因为我说conn.setDoInput(true); 。

有人可以向我提供任何关于为什么我无法获得输入流及其解决方法的建议吗?

错误:


  在messageServlet()中:故障:java.io.IOException:服务器返回的HTTP响应代码:501 for URL:http://://localhost:8000/TestServlet.class


我的代码在下面(我已经注释了引发异常的位置),如果您想知道http:// localhost:8000是我用python脚本设置的Moch服务器,它也是有效的,因为连接并获取输出流不会不会抛出异常。

//this code occurs in my class TextApplet::messageServlet()
//I am attempting to send a string to my servlet class TestServlet,
//then read a string that the servlet sends back
try
{
    URL servletUrl = new URL( "http://localhost:8000/TestServlet.class" );
 URLConnection conn = servletUrl.openConnection();

    conn.setDoInput( true );
    conn.setDoOutput( true );
    conn.setUseCaches( false );
    conn.setDefaultUseCaches (false);
    conn.setRequestProperty ("Content-Type", "application/octet-stream");
    OutputStream out = conn.getOutputStream();

    out.write( message.getBytes() );
    out.flush();
    out.close();

    // receive result from servlet
    InputStream in = conn.getInputStream(); // Exception Occurs HERE
    BufferedReader reader = new BufferedReader(new InputStreamReader( in ));
 String result = reader.readLine();
 in.close();

    return result;
}
catch ( IOException e )
{
    System.out.println( "In messageServlet(): " + e );
    msgBox.setText( msgBox.getText() + "\nIn messageServlet(): Failure: " + e );
}
catch ( Exception e )
{
    System.out.println( "In messageServlet(): " + e );
    msgBox.setText( msgBox.getText() + "\nIn messageServlet(): Failure: " + e );
}

return null;
}

最佳答案

HTTP 501错误表示服务器(至少是servletcontainer内置的默认servlet)在您创建时不理解HTTP请求。原因可能是标题和/或正文不正确。

我不确定发生了什么,但是仅URL http://localhost:8000/TestServlet.class确实显示不正确。看起来很像您已将原始.class文件拖放到公共webcontent文件夹中并尝试访问它。这是没有道理的。 Servlet类应放置在/WEB-INF/classes文件夹中(在包装内!),调用servlet的URL应该在<url-pattern>文件的/WEB-INF/web.xml中定义。

也可以看看


Our Servlets wiki page-包含Hello World示例
How to fire and handle HTTP requests with URLConnection?




与具体问题无关,我宁愿使用Applet#getCodeBase()获取代码库的URL(从那里下载了applet),而不是将其硬编码为URL。假设servlet映射到/myservlet文件中web.xml的URL模式上,那么您需要按照以下步骤在applet中创建URL:

URL url = new URL(getCodeBase(), "myservlet");
// ...

关于java - 在Applet中接收输入流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4977419/

10-08 22:25
查看更多