1

I'm debugging some method which is supposed to call a webservice and return the response.

Already found a lot of information regarding http(s) requests in these threads :

[Can you explain the HttpURLConnection connection process?

[Using java.net.URLConnection to fire and handle HTTP requests

Still one point is not clear to me :

Would a request be sent each time one of this method is called :

connect, getInputStream, getOutputStream, getResponseCode or getResponseMessage

or is it fired only on first occurence of one of these method ?


On my particular case, would this code snippet fire multiple time the request ?

URL url = new URL(webservice);
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {//blabla});

conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

// As far as I understood : request is still not fired there.

System.out.println("callWebService : calling conn.getResponseCode()");
if (conn.getResponseCode() == 400 //Bad Request
    || conn.getResponseCode() == 403 //Forbidden
    || conn.getResponseCode() == 404 //Not Found
    || conn.getResponseCode() == 500 //Internal Server Error
    || conn.getResponseCode() == 501 //Not Implemented
    || conn.getResponseCode() == 502 //Bad Gateway ou Proxy Error
    || conn.getResponseCode() == 503 //Service Unavailable
    || conn.getResponseCode() == 504 //Gateway Time-out
    || conn.getResponseCode() == 505 //HTTP Version not supported)
{
    //handle wrong response
}else{
    System.out.println("callWebService : received correct responseCode ");
    isr = new InputStreamReader(conn.getInputStream());
    br = new BufferedReader(isr);
    output = br.readLine();
    return output;
}

//close operations handled in finally blocks

Yes there is already much to say about not using a local int to store response code, to check only a few of these possible values and so on. This i gonna refactor anyway, I'm only interested in understanding if this request may be fired multiple times.

Community
  • 1
  • 1
Pellekrino
  • 316
  • 1
  • 12

1 Answers1

0

In cases like this you may want to check the source code. Most of JVM classes have included sources, and java.net.HttpURLConnection does.

There is this snip in beginning of method getResponseCode() (as JDK 1.8_71)

/*
 * We're got the response code already
 */
if (responseCode != -1) {
    return responseCode;
}

So its cached. If response is still default value, -1, its executing request to server. But since this behavior is not described in JavaDoc for this method, I would not rely on this and use own integer variable.

JV

JIV
  • 763
  • 1
  • 8
  • 29