HttpURLConnection和HttpsURLConnection 都 找不到setKeepAlive
时间: 2024-02-21 22:47:55 浏览: 12
`setKeepAlive()` 方法在 `HttpURLConnection` 和 `HttpsURLConnection` 中都存在,但是其实现可能因 Java 版本或 Android 版本而异。
在某些版本中,`setKeepAlive()` 方法可能已经被标记为“过时”,因此建议使用替代方法。例如,在 `HttpURLConnection` 中,可以使用 `setConnectTimeout()` 和 `setReadTimeout()` 来设置连接超时和读取超时,而在 `HttpsURLConnection` 中,可以使用 `setSSLSocketFactory()` 来设置 SSL Socket 工厂。
如果您需要确保您的代码在所有环境中均可用,请检查您正在使用的 Java 或 Android 版本,并查看相应的文档,以确定可用的方法。
相关问题
HttpsURLConnection setKeepAlive 找不到
`setKeepAlive()` 方法是 `HttpURLConnection` 类的方法,而不是 `HttpsURLConnection` 类的方法。如果您想在使用 `HttpsURLConnection` 时启用持久连接,则可以使用以下代码:
```java
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "Keep-Alive");
```
这将在请求头中设置 "Connection" 属性为 "Keep-Alive",从而启用持久连接。
jdk8 HttpURLConnection setKeepAlive找不到
在JDK8中,HttpURLConnection类确实没有提供setKeepAlive()方法。相反,它提供了一个名为setFixedLengthStreamingMode()的方法来设置请求体的长度。如果要使用持久连接,请考虑使用HttpClient。
另外,JDK11及更高版本中的HttpURLConnection类已经添加了setKeepAlive()方法,该方法允许您设置是否启用持久连接。如果您可以升级到JDK11或更高版本,则可以使用此方法。