Search code examples
javahttpurlconnectionhttp-request

Java - Perform a http Request POST and GET on the same connection


I have something I am trying to achieve.

I have a web application running on my localhost on port 8080.

I have a HTTP Server running on localhost:9005.

I have a JSP form that passes info to a servlet java class, that in turn performs the HTTP post to the URL on the HTTP Server localhost:9010 with the data string.

What I need to do is perform the POST and GET as part of the same connection. I have them working as two separate calls, but not on the same connection. It needs to be the same connection, as I post data, the HTTP Server takes this data, processes it and outputs unique data to this URL. Therefore the GET needs to be part of the same connection as he POST.

Can anyone please help?

This is my Process Request java code:

    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import javax.servlet.*;
    import javax.servlet.http.*;


    import java.util.List; 
    import java.util.Map.Entry; 

    public class ProcessRequest {

        public void sendRequestToGateway() throws Throwable{

            String message = URLEncoder.encode("OP1387927", "UTF-8");    

            try {           
                URL url = new URL("http://localhost:9005/json");            
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();            
                connection.setDoOutput(true);            
                connection.setRequestMethod("POST");            
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());           
                writer.write("operator=" + message);       
                writer.close();   

                System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
                System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 

                    receiveMessageFromGateway();

                } else {                
                    // Server returned HTTP error code.            
                }   

                //receiveMessageFromGateway();

            } catch (MalformedURLException e) {            
                // ...        
            } catch (IOException e) {           
                    // ...        
            }
        }

        public void receiveMessageFromGateway()  throws Throwable { 


            HttpURLConnection client = null; 
            OutputStreamWriter wr = null; 
            BufferedReader rd = null; 
            StringBuilder sb = null; 
            String line = null; 

            try { 

              URL url = new URL("http://localhost:9005/json"); 
              client = (HttpURLConnection) url.openConnection(); 
              client.setRequestMethod("GET"); 
              client.setDoOutput(true); 
              client.setReadTimeout(10000); 

              client.connect(); 
              System.out.println(" *** headers ***"); 
              for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) { 
                System.out.println(headernew.getKey() + "=" + headernew.getValue()); 
              } 

              System.out.println(" \n\n*** Body ***"); 
              rd = new BufferedReader(new InputStreamReader(client.getInputStream())); 
              sb = new StringBuilder(); 

              while ((line = rd.readLine()) != null) { 
                sb.append(line + '\n'); 
              } 

              System.out.println("body=" + sb.toString()); 

            } finally { 
              client.disconnect(); 
              rd = null; 
              sb = null; 
              wr = null; 
            } 
         }  

    }

Solution

  • In general you can't control connection reuse with HttpUrlConnection. You might be able to cast your connection to the specific implementation class and interfere with it but that's a horribly unstable way of doing it.

    Apache HttpClient is probably a better option, given the requirements.