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

javax.net.ssl.HttpsURLConnection when are the request fired

我正在调试一些应该调用网络服务和 return 响应的方法。

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

[

[

还有一点我不清楚:

每次调用此方法时是否发送请求:

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 来存储响应代码、仅检查其中几个可能的值等等,已经有很多要说的了。无论如何我都会重构这个,我只对了解是否可以多次触发此请求感兴趣。

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

方法 getResponseCode() 开头有这个片段(如 JDK 1.8_71)

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

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

合资企业