仅在Android 20以下的API上,即使设置了连接超时,HTTPS请求也会挂起。

8

我创建了一个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;

如果URL是https,则使用HttpsURLConnection - K Neeraj Lal
不错的建议,但我尝试过了,问题仍然存在。 - user299648
尝试这个:https://dev59.com/OGoy5IYBdhLWcg3wScFB#8655039 - Shivansh
你在主线程中使用网络代码吗?还是使用单独的线程进行网络工作? - H Raval
网络代码不在主线程中。 - user299648
1个回答

6
  1. You're specifying timouts using some unicode charachters. Please try regular numbers like that:

     connection.setConnectTimeout(30000);   
     сonnection.setReadTimeout(30000);
    
  2. Keep in mind "after connect" will not be logged on timeout. Exception will be thrown instead.


感谢您的提醒,在将超时设置为30000之后,我仍然收到了“连接被对等方关闭”的异常消息。 - user299648
@user299648,所以它不再像你之前说的那样挂起来了吗?可能这就是应该的方式。 - Fedor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接