Search code examples
javasocketsservletshttp-parameters

Read HTTP Parameters on TCP port using Java ServerSocket


How would I read the HTTP Request parameters if I send an HTTP Request from a Java Servlet and receive it on a TCP port using ServerSocket. Can anyone please help me on this?

Following is my design

Servlet

GET/POST using HttpURLConnection

    URL url = new URL("http://localhost:2309/");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestProperty("Content-Type", "application/text");
    connection.setRequestProperty("Accept", "application/text");
    connection.setRequestMethod("POST");        
    connection.setRequestProperty("header1", "value1");

at localhost : 2309 I have a ServerSocket up and listening for a request from above servlet. I am trying to read the request but I only read the HTTP Headers, but I do not see the request parameters (I know in above example I am not sending any parameters, I had tried this by getting Output stream of the connection and writing to it).

this is how I tried sending request parameters to my ServerSocket program.

byte[] parameters = someString.getBytes();
        OutputStream outStream = connection.getOutputStream();
        outStream.write(parameters);

Following is my ServerSocket program.

public static void main(String... args) {
    int port = 2309;
    ServerSocket sSocket = new sSocket(port);
    System.out.println("### SERVER IS UP AND RUNNING, WAITING FOR A CLIENT TO CONNECT ON " + port + " ###");
    Socket cSocket = sSocket.accept();
    System.out.println("### CONNECTION WITH THE CLIENT CREATED ###");
    BufferedReader readRequest = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
    PrintWriter writeResponse = new PrintWriter(cSocket.getOutputStream());
    String line = "";
    while (readRequest != null  && (line = readRequest.readLine()) != null) {
        if (line.length() == 0)
            break;
        System.out.println(line);
    }
    writeResponse.write("HTTP/1.0 200 OK\r\n");
    writeResponse.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
    writeResponse.write("Server: Apache/0.8.4\r\n");
    writeResponse.write("Content-Type: text/html\r\n");
    writeResponse.write("Content-Length: 59\r\n");
    writeResponse.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
    writeResponse.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
    writeResponse.write("\r\n");
    writeResponse.write("<TITLE>Example</TITLE>");
    writeResponse.write("<P>This is an example</P>");
}

Following is what I see on my ServerSocket program OUTPUT.

### SERVER IS UP AND RUNNING, WAITING FOR A CLIENT TO CONNECT ON 2309 ###
### CONNECTION WITH THE CLIENT CREATED ###
POST / HTTP/1.1
Content-Type: application/text
Accept: application/text
header1: value1
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.7.0_75
Host: localhost:2309
Connection: keep-alive
### CONNECTION WITH THE CLIENT TERMINATED ###

Can anyone suggest me

  1. how do I read the Request Parameters

  2. Writing to output stream on connection object, will it get me the request parameters right at the place?

  3. Is this a good approach, when I just want to keep an standalone server up, which will be just listening to the requests coming on to single port and serving it [OR] there is any better way through which I can perform this?


Solution

  • I was not able to get the body from HTTP Payload. And probable reason was below line.

    BufferedReader readRequest = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
    

    I changed it to

        public static void main(String... args) {
        int port = 2309;
        sSocket sSocket = new sSocket(port);
        System.out.println("### SERVER IS UP AND RUNNING, WAITING FOR A CLIENT TO CONNECT ON " + port + " ###");
        Socket cSocket = sSocket.accept();
        System.out.println("### CONNECTION WITH THE CLIENT CREATED ###");
        InputStream readRequest = cSocket.getInputStream();
        PrintWriter writeResponse = new PrintWriter(cSocket.getOutputStream());
        byte[] buf = new byte[4096];
        readRequest.read(buf);
        String httpPayload = new String(buf, "UTF-8");
        HttpPayload httpPayloadObject = new HttpPayload(httpPayload);
        Map<String, Object> httpParameters = httpPayloadObject.getHttpPayloadBodyMap();
        PushNotificationEvent event = new PushNotificationEvent(httpParameters);
        event.processEvent();
        writeResponse.write("HTTP/1.0 200 OK\r\n");
        writeResponse.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
        writeResponse.write("Server: Apache/0.8.4\r\n");
        writeResponse.write("Content-Type: text/html\r\n");
        writeResponse.write("Content-Length: 59\r\n");
        writeResponse.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
        writeResponse.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
        writeResponse.write("\r\n");
        writeResponse.write("<TITLE>Example</TITLE>");
        writeResponse.write("<P>This is an example</P>");
    }
    

    the Buffered input stream omitted the body part. Now I get the output as desired

    POST / HTTP/1.1
    Host: 127.0.0.1:2309
    Connection: keep-alive
    Content-Length: 63
    Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
    header1: value1
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW6**strong text**4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
    Content-Type: application/json
    Accept: */*
    Accept-Encoding: gzip, deflate
        en-US,en;q=0.8
    
    {jsondata : {key1:value1_getting_bigger_content,  key2:value2}}
    

    the part which was not showing up in the payload previously is

    {jsondata : {key1:value1_getting_bigger_content,  key2:value2}}
    

    I am still not sure why BufferedReader or BufferedInputStream omits the body