javax.net.ssl.HttpsURLConnection何时触发请求

时间:2016-10-25 10:01:08

标签: java http https httpsurlconnection

我正在调试一些应该调用webservice并返回响应的方法。

在这些主题中已经找到了很多关于http(s)请求的信息:

[Can you explain the HttpURLConnection connection process?

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

我还不清楚一点:

每次调用此方法之一时都会发送请求:

connect,getInputStream,getOutputStream,getResponseCode或getResponseMessage

或仅在第一次出现这些方法时才会被解雇?

就我的具体情况而言,此代码片段会多次触发请求吗?

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

是的,关于不使用本地int存储响应代码,仅检查其中一些可能的值等等,已经有很多话要说了。无论如何我会重构,我只是想了解这个请求是否可以被多次激活。

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可能需要检查源代码。大多数JVM类都包含了源代码,而java.net.HttpURLConnection则包含了源代码。

方法 getResponseCode()(作为JDK 1.8_71)的开头有这个片段

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

所以它的缓存。如果响应仍然是默认值-1,则它对服务器的执行请求。但是由于JavaDoc中没有为此方法描述此行为,因此我不会依赖于此并使用自己的整数变量。

JV