HttpsURLConnection failing intermittently to the same URL

旧巷老猫 提交于 2020-01-13 19:52:51

问题


I think I'm experiencing the same as http://groups.google.com/group/android-developers/msg/9d37d64aad0ee357
This is Android 1.5 SDK. I happen to call several times below code(which is in a method) with the same url and it fails intermittently.
When it fails, there is no exception, the stream is empty so the readConnection fails, and getResponseCode returns -1.
Global caching is disabled, setDefaultUseCaches(false);

I suppose there must be some kind of url connection object pool somewhere.

Any idea on how can I workaround this?

HttpURLConnection connection = null;
    try {
        URL url = new URL(this.url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "basic " +
        Base64Coder.encodeString(user + ":" + password));
        connection.setRequestProperty("User-Agent", userAgent);
        connection.connect();

        readConnection(connection.getInputStream());

        connection.disconnect();
    } catch (IOException ex) {
               reportException(ex, connection.getResponseCode())
    } catch (ParserException ex) {
               reportException(ex, connection.getResponseCode())
    } 

回答1:


The way I fixed this issue was to add the below line...

System.setProperty("http.keepAlive", "false");

...before my connection line...

connection = (HttpURLConnection) url.openConnection();

Good luck!




回答2:


if getResponseCode returns -1 it means that there was a connection error of some sort.



来源:https://stackoverflow.com/questions/2841298/httpsurlconnection-failing-intermittently-to-the-same-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!