0

I use the library GSON to parse the response of a web service in JSON format. In the event that the web service returns me a positive response, I'll return it as a USER Class, otherwise it returns me as an ERROR Class.

I would like, if when I'm trying to get my USER and that fails, you can recover my ERROR with the same HttpResponse but it does not work. Does anyone have an idea?

try {
    //Create an HTTP client
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL);

    //Add your POST data
    List<NameValuePair> post = new ArrayList<NameValuePair>(3);
    post.add(new BasicNameValuePair("login", login));
    post.add(new BasicNameValuePair("pwd", pwd));
    post.add(new BasicNameValuePair("id_tablet", InfoTab.getPhoneInfo(context)));
    httpPost.setEntity(new UrlEncodedFormEntity(post));

    //Perform the request and check the status code
    HttpResponse response = client.execute(httpPost);
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();

        try {
            //Read the server response and attempt to parse it as JSON
            Reader reader = new InputStreamReader(content);

            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();

            User user = gson.fromJson(reader, User.class);

            if(user.getIdLms()==null) {
                Error error = gson.fromJson(reader, Error.class);
                // ERROR TREATMENT
            } else {
                // USER TREATMENT
            }
            content.close();
        } catch (Exception ex) {
            Log.e(getClass().getSimpleName(), "Failed to parse JSON due to: " + ex);
        }
    } else {
        Log.e(getClass().getSimpleName(), "Server responded with status code: " + statusLine.getStatusCode());
    }
} catch(Exception ex) {
    Log.e(getClass().getSimpleName(), "Failed to send HTTP POST request due to: " + ex);
}

2 Answers 2

1

You can cache your JSON once you make a successful call, and on later calls if fails read your JSON from cache.

As a pseudo code you would have.

try
{
            read JSON from server;
            //write JSON to cache;
            //after coding with java
            JSONObject jsonObject = // cast you gson  into JSONObject in a way
            writeJSONToCache( jsonObject  , cacheFolderPath , cahceFileName);
}
catch (ClientProtocolException e) //fail.. no connection or something
{
            read JSON from cache;
}

edit
java code for storing json cache file

public static void writeJSONToCache( JSONObject jsonObject  , String cacheFolderPath , String cahceFileName) throws IOException, JSONException
    {
        String jsonString = jsonObject.toString(4)
        new File(cacheFolderPath).mkdirs();
        File cahceFile = new File(cacheFolderPath, cahceFileName);
        // if file doesnt exists, then create it
        if (!cahceFile.exists())
            cahceFile.createNewFile();          
        FileWriter fileWriter = new FileWriter(cahceFile.getAbsoluteFile());
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(jsonString);
        bufferedWriter.close();
    }
2
  • How can we put a JSON cache? Oct 8, 2013 at 10:24
  • you can save the json you have got from http request into .json file on device, and then you can read from file, ill attach some code you'll need to modify later Oct 8, 2013 at 10:26
0

Why not Combining User.class and Error.class to a Big DataObject.class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.