adit
adit

Reputation: 33644

issue with HttpURLConnection OutputStream

I have the following code:

String urlString = API_URL + "/checkins/add";  
            String inputdata = "v=20111111"+"&venueId="+venueid+"&broadcast="+broadcast+"&oauth_token="+mAccessToken;  
            String content="";  
            try {  
                URL url = new URL( urlString );
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput( true ); 
                con.connect();  

                Log.v("RESPONSE MESSAGE", con.getResponseMessage());

                OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());  
                out.write(inputdata);  
                out.flush();              

and I am getting an error:

Exception: OutputStream unavailable because request headers have already been sent!

why is this?

Upvotes: 3

Views: 2465

Answers (2)

Jörn Horstmann
Jörn Horstmann

Reputation: 34014

When you are calling con.getResponseMessage() in your log statement the http message has to get sent and the response read. So by this time the its to late to add a request body using the OutputStream. Just move the log message after writing the input data and you should be fine.

Upvotes: 4

Siva Charan
Siva Charan

Reputation: 18064

HTTP Methods

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

This is the reason for getting the exception.

Upvotes: -1

Related Questions