我想从Java应用程序调用Servlet。问题是,调用似乎没有到达Servlet。我没有得到任何错误,但没有到达Servlet中的第一个输出“doPost”。如果我在网络浏览器中打开URL,我当然得到了GET不支持的错误等,但至少我看到,有些事情发生了。
我使用以下代码(ActionPackage类只包含参数Vector并且是Serializable):
Java应用程序:
ActionPackage p = new ActionPackage();
p.addParameter("TEST", "VALUE");
System.out.println(p);
URL gwtServlet = null;
try {
gwtServlet = new URL("http://localhost:8888/app/PushServlet");
HttpURLConnection servletConnection = (HttpURLConnection) gwtServlet.openConnection();
servletConnection.setRequestMethod("POST");
servletConnection.setDoOutput(true);
ObjectOutputStream objOut = new ObjectOutputStream(servletConnection.getOutputStream());
objOut.writeObject(p);
objOut.flush();
objOut.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
的Servlet
public class PushServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
ObjectInputStream objIn = new ObjectInputStream(request.getInputStream());
ActionPackage p = null;
try {
p = (ActionPackage) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Servlet received p: "+p);
}
}
任何想法出了什么问题?
感谢。
答案 0 :(得分:7)
URLConnection
方法, get
就会被懒惰地执行。
将以下内容添加到您的代码中实际执行HTTP请求并获取servlet响应正文。
InputStream response = servletConnection.getInputStream();
答案 1 :(得分:0)
尝试在try / catch块中包装doPost的整个主体:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("doPost");
ObjectInputStream objIn = new ObjectInputStream(request.getInputStream());
ActionPackage p = null;
p = (ActionPackage) objIn.readObject();
System.out.println("Servlet received p: "+p);
} catch (Throwable e) {
e.printStackTrace(System.out);
}
}
然后再次查看您的Servlet输出日志文件或窗口以获取可能有用的新异常。
答案 2 :(得分:0)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("doPost");
ObjectInputStream objIn = new ObjectInputStream(request.getInputStream());
ActionPackage p = null;
p = (ActionPackage) objIn.readObject();
System.out.println("Servlet rece p: "+p);
} catch (Throwable e) {
e.printStackTrace(System.out);
}
}