private ActionResult parseJSONResponse(JSONObject response) { if (response == null) { ActionError error = new ActionError(ErrorCode.SERVER_ERROR, "服务器未返回结果"); return new ActionResult(error); } if (!response.has("response")) { ActionError error = new ActionError(ErrorCode.SERVER_ERROR, "服务器返回空,请稍候重试"); return new ActionResult(error); } try { response = response.getJSONObject("response"); if (!response.has("flag")) { ActionError error = new ActionError(ErrorCode.SERVER_ERROR, "服务器未返回响应代码"); return new ActionResult(error); } int flag = response.getInt("flag"); if (flag != 1) { String errorMessage = "请求失败"; if (response.has("msg")) { errorMessage = response.getString("msg"); } ActionError error = new ActionError(ErrorCode.APPLICATOIN_ERROR, errorMessage); return new ActionResult(error); } if (mSecurity && response.has("signature") && response.has("timestr")) { Log.d(tag, "Verifying the data..."); String signature = response.getString("signature"); String timeStr = response.getString("timestr"); String bodyStr = ""; JsonElement body = mGsonObject.get("response").getAsJsonObject().get("body"); if (body != null) { bodyStr = body.toString(); } // String key = PreferenceUtil.getString(mAppContext, // Constants.APP_BINDING_KEY, Constants.APP_DEFAULT_KEY); String clientSignature = Utils.md5(flag + bodyStr + timeStr + getEncryptKey()); if (!clientSignature.equals(signature)) { Log.e(tag, "Verification failed, the data might be modified!!!"); ActionError error = new ActionError(ErrorCode.SECURITY_ERROR, "数据校验未通过!!!"); return new ActionResult(error); } } if (!response.has("body")) { return new ActionResult(""); } JSONObject body = response.getJSONObject("body"); return new ActionResult(createRespObject(body)); } catch (JSONException e) { Log.e(tag, "Failed to parse Json response for request: " + mServiceId, e); ActionError error = new ActionError(ErrorCode.SERVER_ERROR, "服务器数据格式不对: "); return new ActionResult(error); } }
private JsonObject createJSONRequest() throws JSONException, UnsupportedEncodingException { JsonObject request = new JsonObject(); String timeStr = Utils.formatDate("yyyy-MM-dd HH:mm:ss", new Date()); JSONObject actionBody = removeInvalidParas(getRequestBody(timeStr)); JsonObject requestBody = new JsonParser().parse(actionBody.toString()).getAsJsonObject(); request.add("timestr", new JsonPrimitive(timeStr)); request.add( "signature", new JsonPrimitive(Utils.md5(requestBody.toString() + timeStr + getEncryptKey()))); request.add("body", encodeBody(requestBody)); JsonObject wrapper = new JsonObject(); wrapper.add("request", request); return wrapper; }