简体   繁体   English

无法访问服务器时程序关闭

[英]program close when failing to reach server

I'm new to Android and programming in general. 我是Android和编程领域的新手。 I've built an activity that runs a service that connects to a PHP script to pull some data from a server. 我建立了一个活动,该活动运行一个服务,该服务连接到PHP脚本以从服务器提取一些数据。 The problem is that when the program can't reach the server it crashes. 问题在于,当程序无法访问服务器时,它会崩溃。 How do I prevent the program from crashing each time it can't reach the php script? 如何防止程序每次无法到达php脚本时崩溃? Thanks. 谢谢。

The relevant part of the code: 代码的相关部分:

private String getServerData(String returnString) {

      InputStream is = null;

      String result = "";


       try{
               HttpClient httpclient = new DefaultHttpClient();
               HttpPost httppost = new HttpPost(returnString);
               HttpResponse response = httpclient.execute(httppost);
               HttpEntity entity = response.getEntity();
               is = entity.getContent();

       }catch(Exception e){
               Log.e("log_tag", "Error in http connection "+e.toString());
       }

       //convert response to string
       try{
               BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
               StringBuilder sb = new StringBuilder();
               String line = null;
               while ((line = reader.readLine()) != null) {
                       sb.append(line + "\n");
                           }
               is.close();
               result=sb.toString();

           }catch(Exception e){
               Log.e("log_tag", "Error converting result "+e.toString());
       }

       return result; 

   }    

.

08-29 13:10:01.571: ERROR/AndroidRuntime(1116): <p>The requested URL /getAvgScore1.php was not found on this server.</p>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): <p>Additionally, a 404 Not Found
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): error was encountered while trying to use an ErrorDocument to handle the request.</p>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): </body></html>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at org.apache.harmony.luni.util.FloatingPointParser.initialParse(FloatingPointParser.java:132)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:310)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at java.lang.Float.parseFloat(Float.java:327)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at java.lang.Float.valueOf(Float.java:368)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at iAndroid.RYCQ.rankservice.onCreate(rankservice.java:46)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2465)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     ... 10 more
08-29 13:10:01.581: INFO/Process(583): Sending signal. PID: 1116 SIG: 3
08-29 13:10:01.581: INFO/dalvikvm(1116): threadid=7: reacting to signal 3
08-29 13:10:01.591: INFO/dalvikvm(1116): Wrote stack trace to '/data/anr/traces.txt'
08-29 13:10:10.634: WARN/ActivityManager(583): Launch timeout has expired, giving up wake lock!
08-29 13:10:10.634: WARN/ActivityManager(583): Activity idle timeout for HistoryRecord{436eed60 {iAndroid.RYCQ/iAndroid.RYCQ.finalresult}}
08-29 13:10:20.698: WARN/ActivityManager(583): Timeout executing service: ServiceRecord{437c8d88 iAndroid.RYCQ/.rankservice}

Probably you'll just have to catch whatever exception is being thrown when connecting to your server fails. 连接到服务器失败时,可能只需要捕获引发的任何异常即可。 You need to post the code that you are currently using though. 但是,您需要发布当前正在使用的代码。 Without being able to see what you've done we can only guess randomly at what will fix it. 无法看到您所做的事情,我们只能随机猜测会解决什么问题。

    public static InputStream fetch(String urlString) throws MalformedURLException, IOException {
    HttpParams httpParameters = new BasicHttpParams();

    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

You have to put timeoutConnection and timeoutSocket values so that device won't be waiting for response forever. 您必须放置timeoutConnection和timeoutSocket值,以使设备不会永远等待响应。 More info about fields are accessible here . 有关字段的更多信息可在此处访问。

If there is an Exception thrown in the 1st try block, you instanciate a BufferedReader on a null InputStream . 如果在第一个try块中引发了Exception,则可以在null InputStream上实例化BufferedReader Have only one try/catch block, or properly quit the method in the first catch . 仅具有一个try/catch块,或在第一个catch正确退出该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM