我创建了一个java.net.HttpURLConnection
,但是它在connection.connect()
这一行挂起,即使我设置了连接超时。记录了“b4 connect”,但从未记录“after connect”。我已在API 21及以上进行了测试并正常工作,但在API 16-19上的测试中遇到了此问题。以下是我的代码。该请求使用https,后端使用标准的nginx https配置。
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
connection.setRequestMethod("GET");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
connection.setConnectTimeout('\uea60');
connection.setReadTimeout('\uea60');
connection.setInstanceFollowRedirects(false);
Log.d(TAG, "b4 connect");
connection.connect();
Log.d(TAG, "after connect");
if(connection.getResponseCode() == 200) {
return IOUtils.toString(connection.getInputStream(), "UTF-8");
}
} catch (Exception var) {
throw new Exception(var.getMessage());
} finally {
connection.disconnect();
}
return null;
https
,则使用HttpsURLConnection
。 - K Neeraj Lal