我已将Wi-Fi IP更改为无法连接。我希望当 5 秒过去时做其他事情,但它等待大约 20 秒。
URL url = null;
HttpsURLConnection conn = null;
try {
url = new URL("MY_URL");
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("msg", String.valueOf(jsonArray)));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) conn.getContent(), "UTF-8"));
String response = reader.readLine();
来自文档
警告:如果主机名解析为多个 IP 地址,Android 的默认 HttpURLConnection 实现将按 RFC 3484 顺序尝试每个 IP 地址。如果连接到其中每个地址失败,则在连接尝试引发异常之前将经过多个超时。同时支持 IPv6 和 IPv4 的主机名始终至少具有 2 个 IP 地址。
这意味着,如果主机涉及"n"个IP地址,则需要n*milliseconds
时间,而不是milliseconds
您挑衅。