我正在将一个字符串从 Applet 发送到 Servlet。当我从 URLConnection 获取输出流时,我收到抛出异常 java.net.UnknownServiceException: 协议(protocol)不支持输出
一些背景信息;我正在使用 Eclipse,我通过在 Eclipse 和我自己制作的 html 页面中运行它来测试小程序,它们抛出相同的错误。我已经下载了正确的 Java Web SDK。也许我需要设置我的 hxxp://8008... 服务器?
为什么会发生这种情况以及如何解决?我需要签署我的小程序才能使其正常工作吗?
这是我的代码,我已经评论了抛出异常的位置:
public String messageServlet()
{
try
{
URLConnection conn = connectToServlet();
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream(); // Exception thrown here: UnknownServiceException: protocol doesn't support output
ObjectOutputStream objOut = new ObjectOutputStream( out );
objOut.writeObject( message );
objOut.flush();
objOut.close();
System.out.println( "1" );
// receive result from servlet
InputStream instr = conn.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String result = (String) inputFromServlet.readObject();
inputFromServlet.close();
instr.close();
System.out.println( "1" );
return result;
}
catch ( IOException e )
{
System.out.println( "In messageServlet(): " + e );
msgBox.setText( msgBox.getText() + "\nIn messageServlet(): " + e );
}
catch ( Exception e )
{
System.out.println( "In messageServlet(): " + e );
msgBox.setText( msgBox.getText() + "\nIn messageServlet(): " + e );
}
return null;
}
public URLConnection connectToServlet()
{
try
{
URL servletUrl = new URL( getCodeBase(), "echo" );
URLConnection conn = servletUrl.openConnection();
conn.setDoInput( true );
conn.setDoOutput( true );
conn.setUseCaches( false );
conn.setRequestProperty( "Content-Type", "application/x-java-serialized-object" );
return conn;
}
catch ( IOException e )
{
System.out.println( "In connectToServlet(): " + e );
}
return null;
}
最佳答案
您有两个潜在的问题:
网络服务器未启动。确保它已启动并且 http://localhost:8008/context/servleturl在您的网络浏览器中运行良好。
除此之外,常见的做法是不在小程序中对基本域进行硬编码,这会使其不可移植(每次移动域时都需要修复/更改它)。只需从继承的 Applet#getCodeBase()
中获取即可方法。使用它作为您的 servlet URL 的基础。
URL servlet = new URL(getCodeBase(), "servleturl");
// ...
这里 getCodeBase()
因此返回类似 http://localhost:8008/context 。
除此之外,我更喜欢通过 HTTP 发送纯文本、JSON 或 XML 格式,而不是 Java 特定的二进制数据。它具有更好的可重用性,并且更易于预处理/后处理。您希望在字符串中来回发送一些字符。只需将其作为 HTTP 请求参数发送,然后让 servlet 通过 request.getParameter()
等方式获取它。为什么要为此使用 Java 序列化?
关于java - 将对象发送到 Servlet 会引发我无法解决的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4950874/