babb
babb

Reputation: 423

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

    }

Upvotes: 0

Views: 4988

Answers (3)

tiagotam
tiagotam

Reputation: 181

You can use Apache HTTP Client for this. Its very simple.

If you are using maven, just add the following lines into your POM file:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.3</version>
</dependency>   

In this example, I'm submitting a POST request and after that a GET request.

Take a look:

public static String get(String p_url) throws IOException
{       

        CloseableHttpClient httpclient = HttpClients.createDefault();

        // First request: POST
        HttpPost httpPost = new HttpPost("http://the-api-url.com/Login/Auth&token=12345"));
        CloseableHttpResponse response_post = httpclient.execute(httpPost);                 
        System.out.println(response_post.getStatusLine());          
        HttpEntity entity_post = response_post.getEntity();         
        System.out.println(EntityUtils.toString(entity_post));

        // Second request: GET
        HttpGet httpGet = new HttpGet(p_url);
        CloseableHttpResponse response_get = httpclient.execute(httpGet);  
        System.out.println(response_get.getStatusLine());           
        HttpEntity entity_get = response_get.getEntity();           
        System.out.println(EntityUtils.toString(entity_get));

        response_post.close();
        response_get.close();           
        return EntityUtils.toString(entity_get);             
    }

Upvotes: 0

biziclop
biziclop

Reputation: 49814

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.

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

Why don't you just return the result from the original POST?

Upvotes: 3

Related Questions