5

我想从 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();
    }
}

小服务程序:

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);       
}

}

任何想法出了什么问题?

谢谢。

4

3 回答 3

7

URLConnection仅在您调用任何方法时才延迟执行get

将以下内容添加到您的代码中以实际执行 HTTP 请求并获取 servlet 响应正文。

InputStream response = servletConnection.getInputStream();

也可以看看:

于 2010-12-03T21:10:18.543 回答
0

尝试将 doPost 的整个主体包装在 try/catch 块中:

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 输出日志文件或窗口,寻找可能有帮助的新异常。

于 2010-12-03T21:11:05.070 回答
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);
    }
}
于 2014-07-30T09:52:45.253 回答