黑莓 如果失败重试连接的最佳方法?

发布于 2024-11-04 20:59:06 字数 4950 浏览 0 评论 0原文

我有以下代码,如果在处理请求时发生异常,我希望能够重新启动线程。

线程的 run 方法中如下:

int status = httpConn.getResponseCode();

                        if (status == HttpConnection.HTTP_OK) {
                            // Is this html?
                            String contentType = httpConn
                                    .getHeaderField(HEADER_CONTENTTYPE);
                            boolean htmlContent = (contentType != null && contentType
                                    .startsWith(CONTENTTYPE_TEXTHTML));

                            InputStream input = s.openInputStream();

                            byte[] data = new byte[1000];
                            int len = 0;
                            int size = 0;
                            StringBuffer raw = new StringBuffer();

                            while (-1 != (len = input.read(data))) {
                                // Exit condition for the thread. An
                                // IOException
                                // is
                                // thrown because of the call to
                                // httpConn.close(),
                                // causing the thread to terminate.
                                if (_stop) {
                                    httpConn.close();
                                    s.close();
                                    input.close();
                                }
                                raw.append(new String(data, 0, len));
                                size += len;
                            }

                            // raw.insert(0, "bytes received]\n");
                            // raw.insert(0, size);
                            // raw.insert(0, '[');
                            content = raw.toString();

                            if (htmlContent) {
                                content = prepareData(raw.toString());
                            }
                            input.close();
                        } else {
                             try{
                                httpConn.close();
                             }catch (Exception e) {
                                // TODO: handle exception
                            }
                             errorDialog(status+", status code");

                            retryFeed(getUrl(), "Network error. Retrying...");

                        }
                        s.close();
                    } else {



                        errorDialog("Sorry Insufficient Network Coverage.");
                        return;
                    }
                } catch (IOCancelledException e) {

                      errorDialog(e.getMessage());
                    retryFeed(getUrl(), "Network error. Retrying...");
                } catch (IOException e) {

                    errorDialog(e.getMessage());
                    retryFeed(getUrl(), "Network error. Retrying...");
                }

如果连接失败,重试连接的最安全方法是什么?

谢谢。

//New 这是错误线程。检查连接中的错误...这有帮助吗?这是最有效的方法吗?谢谢..

/错误线程 - 检查错误的线程/ 私有类 ErrorThread 扩展 Thread { 私有静态最终 int 超时 = 3000; // 每 3 秒 私有布尔 hasException = false; 私有字符串_theUrl;

    /**
     * Stops this thread from listening for messages
     */
    private synchronized void stop()
    {
       hasException =false;
    }   

    /**
     * Listens for incoming messages until stop() is called
     * @see #stop()
     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        try 
        {    

              while (true) {



                  if((hasException==true))
                  {
                      // Synchronize here so that we don't end up creating a connection that is never closed.
                    errorDialog("Will Fetch new");
                      synchronized(this)  
                      {
                          hasException=false;
                            if (!_connectionThread.isStarted()) {


                            fetchPage(_theUrl);
                        } else {

                            createNewFetch(_theUrl);

                        }

                      }

                }
                    try {

                        //errorDialog("No exception.");

                        sleep(TIMEOUT);

                    } catch (InterruptedException e) 
                    {

                        errorDialog("Exceptions"+e.toString()+e.getMessage());
                        System.exit(1);
                        //System.exit(0);/*Kill System*/
                    }


              }




        } 
        catch (Exception except)
        {                             

        }
    }

    public void setActive(boolean exception,String url)
    {
        this.hasException=exception;
        this._theUrl=url;

    }

}

I have the following code, i want to be able to restart the thread if an exception occurred while processing a request.

The following in the run method of a thread:

int status = httpConn.getResponseCode();

                        if (status == HttpConnection.HTTP_OK) {
                            // Is this html?
                            String contentType = httpConn
                                    .getHeaderField(HEADER_CONTENTTYPE);
                            boolean htmlContent = (contentType != null && contentType
                                    .startsWith(CONTENTTYPE_TEXTHTML));

                            InputStream input = s.openInputStream();

                            byte[] data = new byte[1000];
                            int len = 0;
                            int size = 0;
                            StringBuffer raw = new StringBuffer();

                            while (-1 != (len = input.read(data))) {
                                // Exit condition for the thread. An
                                // IOException
                                // is
                                // thrown because of the call to
                                // httpConn.close(),
                                // causing the thread to terminate.
                                if (_stop) {
                                    httpConn.close();
                                    s.close();
                                    input.close();
                                }
                                raw.append(new String(data, 0, len));
                                size += len;
                            }

                            // raw.insert(0, "bytes received]\n");
                            // raw.insert(0, size);
                            // raw.insert(0, '[');
                            content = raw.toString();

                            if (htmlContent) {
                                content = prepareData(raw.toString());
                            }
                            input.close();
                        } else {
                             try{
                                httpConn.close();
                             }catch (Exception e) {
                                // TODO: handle exception
                            }
                             errorDialog(status+", status code");

                            retryFeed(getUrl(), "Network error. Retrying...");

                        }
                        s.close();
                    } else {



                        errorDialog("Sorry Insufficient Network Coverage.");
                        return;
                    }
                } catch (IOCancelledException e) {

                      errorDialog(e.getMessage());
                    retryFeed(getUrl(), "Network error. Retrying...");
                } catch (IOException e) {

                    errorDialog(e.getMessage());
                    retryFeed(getUrl(), "Network error. Retrying...");
                }

What is the safest way to retry the connection if failed?

Thanks.

//New This is the Error thread. That check for errors in the connection... will this help? and is it the most efficient method? thanks..

/Error Thread - Thread to check errors/
private class ErrorThread extends Thread {
private static final int TIMEOUT = 3000; // EVERY 3 Seconds
private boolean hasException = false;
private String _theUrl;

    /**
     * Stops this thread from listening for messages
     */
    private synchronized void stop()
    {
       hasException =false;
    }   

    /**
     * Listens for incoming messages until stop() is called
     * @see #stop()
     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        try 
        {    

              while (true) {



                  if((hasException==true))
                  {
                      // Synchronize here so that we don't end up creating a connection that is never closed.
                    errorDialog("Will Fetch new");
                      synchronized(this)  
                      {
                          hasException=false;
                            if (!_connectionThread.isStarted()) {


                            fetchPage(_theUrl);
                        } else {

                            createNewFetch(_theUrl);

                        }

                      }

                }
                    try {

                        //errorDialog("No exception.");

                        sleep(TIMEOUT);

                    } catch (InterruptedException e) 
                    {

                        errorDialog("Exceptions"+e.toString()+e.getMessage());
                        System.exit(1);
                        //System.exit(0);/*Kill System*/
                    }


              }




        } 
        catch (Exception except)
        {                             

        }
    }

    public void setActive(boolean exception,String url)
    {
        this.hasException=exception;
        this._theUrl=url;

    }

}

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

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

发布评论

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

评论(1

萌辣 2024-11-11 20:59:06

如果连接失败,通常您需要关闭它,暂停一小会儿,然后重试。暂停的目的是防止您的设备投入过多的资源来尝试连接有问题的服务器。

If the connecrtion fails, typically, you want to close it, pause a small time, and retry. The purpose of the pause is to prevent your device from devoting excessive resources to trying to connect to a server that's having issues.

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