How to post to a servlet without reading the inputstream

Discussions

Web tier: servlets, JSP, Web frameworks: How to post to a servlet without reading the inputstream

  1. I have an application that posts a string to the servlet. Then the doPost of the servlet writes the string onto a file.

    The problem is-> if my application does not get the inputstream from the servlet, the doPost of the servlet is not invoked. But if the application reads the inputstream, the servlet's doPost works fine.

    I've attached the code for both the application and the servlet. Is there a way for the application to post the string without having to read the from the inputstream?

    code for application:
    <pre>
    public void sendToServlet() throws Exception{
    URL url = new URL(servletURL.);
    URLConnection urlconn = url.openConnection();
    urlconn.setDoOutput(true);
    PrintWriter out = new PrintWriter( urlconn.getOutputStream(), true);
    out.println("requestmsg="+sMsgBatch);
    out.flush();
    out.close();
    /////////// I WANT TO REMOVE THE FOLLOWING PART ////////////
    try{
    BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) {}
    in.close(); }catch(Exception e){
    e.printStackTrace();
    }
    //////////REMOVE UNTIL HERE////////////
    }
    </pre>

    code for the servlet:

    <pre>
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

    try{
    String param = req.getParameter("requestmsg");

    ///// I WANT TO REMOVE THE FOLLOWING PART////
    resp.setContentType("text/html");
    PrintWriter out = new PrintWriter(resp.getOutputStream(), true);
    out.println("ack");
    out.close();
    //////REMOVE UNTIL HERE//////////

    PrintWriter fwriter = new PrintWriter(new FileOutputStream("logfile.txt", true), true);
    fwriter.println(param);
    fwriter.close();
    </pre>

    Why is it that if I remove the "BufferedReader in = new BufferedReader....." from the application, and "PrintWriter out = new PrintWriter(resp.getOutputStream....." is removed from the servlet, the doPost of the servlet is not invoked?

    Pls advise. Thanks.
  2. I don't think what you want is possible. From my experience with URLConnection, the information in the OutputStream doesn't physically get sent until you make the call to getInputStream(). I searched long and far for a way to force URLConnection to send the request, but the only way I could find to send it was to get grab the InputStream. If you find a way, please send me a message.

    One way you could achieve this would be to bypass URLConnection and write your protocol handler for HTTP using Sockets.

    Andy Nguyen
    anguyen@itginc.com