Android cannot send a GET request with HttpURLConnection

I am trying to use HttpURLConnection in my application. I set my request method to "GET", but when I try to get the output stream, the method changes to "POST"! I'm not sure if this is the reason, but my JSON server (I use JAX-RS) returns a blank page when I send a request using "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 the answer. Eric

+3
source share
2 answers

GET ... POST. , ... doc getOutputStream : " " POST "" ".

GET, URL .

+8

con.setDoOutput(true); . - GET

HttpURLConnection GET . POST, setDoOutput(true).

URL

Android HTTPURLConnection Class

+4

Source: https://habr.com/ru/post/1770689/


All Articles