Cafe
Cafe

Reputation: 61

Java Console program wanting to interact with the Servlet

I'm basically implementing a java console program that sends a HTTP request to the servlet. This code runs but does not give me any output. I have two questions here-

After url.openConnection() I see the value of the the 'connected' field in httpConn object and it says false. But if I remove this comment

    //int responsecode = httpConn.getResponseCode();   

the status code of 200 is returned (success). What does this mean? Has the connection been established or not? When I telnet - o localhost 8080 it says 'Press any key to continue' and when I do so it says 'Connection with the host lost' Also, when the above piece of code is executed the console shows this

null
null
Servlet Reached

and I get the exception below (after the entire program has run in debugging mode)

java.net.ProtocolException: Cannot write output after reading input.

and when I finish executing the next line of code (debugging mode)

StringBuffer requestParams = new StringBuffer();

the console no longer shows the output. What exactly is happening?

An additional question - Right now I'm sending strings as parameters in the HTTP POST message but how would I send entire objects? Would I have to use serialization? Any help would be hugely appreciated.

package tutorial;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.net.*;
import java.util.Iterator;

class HttpUtility{

    private static HttpURLConnection httpConn;

    public static HttpURLConnection sendPostRequest(String requestURL,
            ArrayList list) throws IOException {

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();

        //int responsecode = httpConn.getResponseCode();       
        //httpConn.setDoInput(true); // true indicates the server returns response

        StringBuffer requestParams = new StringBuffer();

        if (list != null && list.size() > 0) {

            httpConn.setDoOutput(true); // true indicates POST request
            // creates the list string, encode them using URLEncoder
            Iterator iter = list.iterator();
            int index=0;

            while (iter.hasNext()) {
                String lValue = (String) iter.next();
                requestParams.append(URLEncoder.encode("params"+ index++, "UTF-8"));
                requestParams.append("=").append(
                        URLEncoder.encode(lValue, "UTF-8"));
                requestParams.append("&");
            }

            System.out.println(requestParams.toString());
            String requestParam = requestParams.toString();

            DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
            wr.writeBytes(requestParam);
            wr.flush();
            wr.close();

            /*
            OutputStream ops = httpConn.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(ops);           
            writer.write(requestParams.toString());
            writer.flush();
            */

            /*
            OutputStream os = httpConn.getOutputStream();
            os.write(requestParam.getBytes());
            os.flush();
            os.close();
            */
        }

        return httpConn;
    }

    public static void disconnect() {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
}


class ConsoleHttpRequest {

    public static String requestURL;

    public static void main(String[] args) {    

        ArrayList list = new ArrayList();

        requestURL = "http://localhost:8080/ServletTutorial/ConsoleToServlet"; // No Exception but no connection
        //requestURL = "https://localhost:8080/ServletTutorial/ConsoleToServlet"; //javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
        //requestURL = "http://localhost"; // java.net.ConnectException: Connection refused: connect
        //requestURL="https://10.167.7.178"; // java.net.ConnectException: Connection refused: connect
        //requestURL="http://www.google.com"; // No Exception but no connection as well     

        list.add("Welcome");
        list.add("to");
        list.add("the");
        list.add("World");
        list.add("of");
        list.add("Java");
        list.add("Programming");

        try {
            HttpUtility.sendPostRequest(requestURL, list);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HttpUtility.disconnect();
    }
}

This is the servlet that receives the request from the console program and simply prints in the console.

package tutorial;

    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     * Servlet implementation class ConsoleToServlet
     */
    public class ConsoleToServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            String s=request.getParameter("params1");
            System.out.println(s);
            System.out.println("Servlet Reached");
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            String s=request.getParameter("params1");
            System.out.println(s);
            doPost(request,response);
        }

    }

Upvotes: 0

Views: 818

Answers (1)

柯鴻儀
柯鴻儀

Reputation: 623

why got 'false' value after "url.openConnection(...)"

after checking with debugtool and tcpdump**(sudo tcpdump -s 0 -A port 80)**, I found that the http request header is not sent when calling openConnection,just after you start reading the inputstream ,the http request from client will be sent .

about ProtocolException

if you call "httpConn.getResponseCode()",it means the http response header was sent to client , so you can't send http request (unless you use the "pipeline" feature of http protocol,but it must be supported by server side also)

send entire objects
try it :

    HttpURLConnection httpConn =(HttpURLConnection) url.openConnection();       
    httpConn.setDoOutput(true);
    ObjectOutputStream objOts=new ObjectOutputStream(httpConn.getOutputStream());
    objOts.writeObject(new Object());
    objOts.close();

Upvotes: 1

Related Questions