我使用库 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);
}