0

我使用库 GSON 以 JSON 格式解析 Web 服务的响应。如果 Web 服务向我返回肯定响应,我会将其作为 USER 类返回,否则它会作为 ERROR 类返回。

我想,如果当我尝试获取我的 USER 并且失败时,您可以使用相同的 HttpResponse 恢复我的错误,但它不起作用。有人有想法吗?

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);
}
4

2 回答 2

1

成功调用后,您可以缓存 JSON,如果失败,则可以在以后的调用中从缓存中读取 JSON。

作为一个伪代码,你会有。

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;
}

编辑
用于存储 json 缓存文件的 java 代码

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();
    }
于 2013-10-08T10:12:10.363 回答
0

为什么不将 User.class 和 Error.class 组合成 Big DataObject.class?

于 2013-10-08T10:10:41.923 回答