Search code examples
javaurlhttpurlconnectionprotocolexception

Must I Get The Response Code From The Server?


I have the following code

URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
if(conn.getResponseCode() == 200){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
} 
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();

If I am not interested in the response from the server, can I remove the following code?

 if(conn.getResponseCode() == 200){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
} 

Considering that the code, in it's entirety as it is, causes a java.net.ProtocolException, is there a way to still grab the server response and execute conn.getOutputStream();? In what order? What are the consequences of not obtaining the response aside from the obvious reporting concerns?


Solution

  • The problem is that once you get the response code, you have sent your post. In your code, you don't write anything to the output stream before you get the response. So, you are essentially sending nothing over the post (just that header info), getting the response code, and then trying to write to it again, which is not allowed. What you need to do is write to the output stream first, and then get the response code like so:

    public static void main(String[] args) throws IOException {
        URL url = new URL(pushURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/restService");
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        String input = writer.getBuffer().toString();
        OutputStream os = conn.getOutputStream();
        for (char c : input.toCharArray()) {
            os.write(c);
        }
        os.close();
    
        if(conn.getResponseCode() == 200){
            System.out.println("Success");
        } else {                 
            System.out.println("Time out set for 30 seconds");
        } 
    }
    

    Here's a little tutorial:

    Reading and Writing Tutorial