HttpURLConnection的奇怪行为

时间:2016-09-21 08:20:56

标签: android

我有一个非常简单的方法从url获取InputStream:

private InputStream request(String uri) {
    Log.d(TAG, "initialize request: "+uri);
    try {
        URL url = new URL(uri));
        Log.d(TAG, "initialize req: "+url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        Log.d(TAG, "initialize open conn");
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            Log.d(TAG, "initialize return is");
            return connection.getInputStream();
        } else {
            Log.d(TAG, "initialize: fail");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.d(TAG, "initialize: what happened?");
    return null;
}

它过去工作完美。但现在,当我尝试使用它时,出于某种原因,它会停在&connection; getResponseCode()'上。刚停下来,没有别的事情发生。日志如下所示:

  

tag:initialize req:http://uri.provided.to.method

     

tag:初始化open conn

就是这样。它确实停在那里,不会打印或返回任何其他内容。对于' connection.getResponseMessage()'具有相同的效果。任何想法为什么会发生以及如何解决它?

1 个答案:

答案 0 :(得分:0)

好的,问题解决了。在网址准备好之前,显然连接太早了。

相关问题