Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android can't send GET request with HttpURLConnection

I'm trying to use an HttpURLConnection in my application. I set my request method to 'GET', but when I try to retrieve the output stream then the method is changed to 'POST' ! I'm not sure that is the reason, but my JSON server (I use JAX-RS) returns a blank page when I send a request using a 'POST'.

Here is a snippet of my code:

// Create the connection
HttpURLConnection con = (HttpURLConnection) new URL(getUrl() + uriP).openConnection();
// Add cookies if necessary
if (cookies != null) {
  for (String cookie : cookies) {
    con.addRequestProperty("Cookie", cookie);
    Log.d("JSONServer", "Added cookie: " + cookie);
  }
}
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
// Add 'Accept' property in header otherwise JAX-RS/CXF will answer a XML stream
con.addRequestProperty("Accept", "application/json");

// Get the output stream
OutputStream os = con.getOutputStream();

// !!!!! HERE THE REQUEST METHOD HAS BEEN CHANGED !!!!!!
OutputStreamWriter wr = new OutputStreamWriter(os);
wr.write(requestP);
// Send the request
wr.flush();

Thanks for you answer. Eric

like image 335
Eric Avatar asked Sep 02 '26 13:09

Eric


2 Answers

But GET requests are supposed to have no content... by writing to the connections output stream you are changing the nature of the request to a POST. The library is being quite helpful in spotting that you are doing this... the doc for getOutputStream explicitly states "The default request method changes to "POST" when this method is called."

If you need to send data up to the server in the GET then it needs to be encoded in URL parameters in the normal way.

like image 196
Reuben Scratton Avatar answered Sep 05 '26 17:09

Reuben Scratton


Remove con.setDoOutput(true); from your code. Then web service request will works fine with GET method

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called.

The above comment can be found within the below URL

Android HTTPURLConnection Class

like image 43
prodeveloper Avatar answered Sep 05 '26 17:09

prodeveloper