我想从 Java 应用程序调用 Servlet。问题是,该调用似乎没有到达 Servlet。我没有收到任何错误,但没有到达 Servlet 中的第一个输出“doPost”。如果我在网络浏览器中打开 URL,我当然会得到不支持 GET 等错误,但至少我看到,发生了一些事情。
我使用以下代码(ActionPackage 类仅包含参数向量并且是可序列化的):
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);
}
}
有什么想法出了什么问题吗?
Thanks.
URLConnection
仅当您调用任何一个时才延迟执行get
方法。
将以下内容添加到您的代码中actually执行 HTTP 请求并获取 servlet 响应正文。
InputStream response = servletConnection.getInputStream();
也可以看看:
- 如何使用java.net.URLConnection触发并处理 HTTP 请求? https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)