【问题标题】:javax.net.ssl.HttpsURLConnection when are the request firedjavax.net.ssl.HttpsURLConnection 请求何时触发
【发布时间】:2026-02-20 01:55:01
【问题描述】:

我正在调试一些应该调用网络服务并返回响应的方法。

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

[Can you explain the HttpURLConnection connection process?

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

我还有一点不清楚:

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

connect、getInputStream、getOutputStream、getResponseCode 或 getResponseMessage

还是仅在第一次出现这些方法之一时触发?


在我的特定情况下,此代码 sn-p 会多次触发请求吗?

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

【问题讨论】:

  • 请求被触发一次。

标签: java http https httpsurlconnection


【解决方案1】:

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

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

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

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

合资

【讨论】:

    最近更新 更多