HttpsURLConnection 间歇性地失败到同一 URL

发布于 2024-09-02 01:31:09 字数 1098 浏览 5 评论 0原文

我想我正在经历同样的事情 http://groups.google.com/group/android-developers/msg/ 9d37d64aad0ee357
这是Android 1.5 SDK。 我碰巧在下面的代码(在一个方法中)中调用了几次 相同的网址,但它间歇性失败。
当失败时,也不例外,流是空的,所以 readConnection 失败,getResponseCode 返回 -1。
禁用全局缓存,setDefaultUseCaches(false);

我想某处一定有某种 url 连接对象池。

知道如何解决这个问题吗?

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())
    } 

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())
    } 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昔梦 2024-09-09 01:31:09

我解决这个问题的方法是添加以下行...

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

...在我的连接线之前...

connection = (HttpURLConnection) url.openConnection();

祝你好运!

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!

花落人断肠 2024-09-09 01:31:09

如果 getResponseCode 返回 -1,则意味着存在某种连接错误。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文