Handle Server Response in Android

后端 未结 3 740
滥情空心
滥情空心 2021-01-16 16:47

In my application I am fetching data using webservices.But when the server is down or not in active state it gives response code 500 and my application force close.

相关标签:
3条回答
  • 2021-01-16 17:15

    At the same time you should check the Response code, by using this code you can easily find out whether the request has made successful or failed due to server down or any other reason.

    You can check the response status code by using:

    response.getStatusLine().getStatusCode();
    
    0 讨论(0)
  • 2021-01-16 17:25

    After seeing the logcat you have posted, I feel you are fetching a JSON String as a response. When you get the response you want you will need to parse it.

    So, in order that you are not held up afterwards in your code, I am helping you to continue after you get your response by giving following example of mine:

    In one of my projects the response I got from the web service was:

    {"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

    In order to parse I did the following:

          JSONObject jsonobject = new JSONObject(result);
          JSONArray array = jsonobject.getJSONArray("checkrecord"); 
          int max = array.length();
          for (int j = 0; j < max; j++) 
       {
          JSONObject obj = array.getJSONObject(j);
          JSONArray names = obj.names();
    
         for (int k = 0; k < names.length(); k++) 
       {
          String name = names.getString(k);
          String value= obj.getString(name);  
    
       }
    

    My JSONObject looks like this:

    {"Table1":[],"checkrecord":[{"missed":34,"attended":12,"percentage":40,"rollno":"abc2"}]}

    This is what the @gwa was trying to suggest. I just gave a code sample to you. Get your result first and determine whether it is valid.

    Hope it helps

    Cheers

    0 讨论(0)
  • 2021-01-16 17:30

    The problem is that you are creating a JSON object using a response which is empty or does not represent a json string.

    So, you should create a JSON object based on your response if:

    - the status code is 200
    - the response is not empty
    - the response starts with '['
    
    0 讨论(0)
提交回复
热议问题