HttpUtils.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * *************************************************
  3. * Copyright (c) 2018 QMTH. All Rights Reserved.
  4. * Created by Deason on 2018-07-17 17:32:00.
  5. * *************************************************
  6. */
  7. package cn.com.qmth.examcloud.app.utils;
  8. import cn.com.qmth.examcloud.app.model.Constants;
  9. import cn.com.qmth.examcloud.app.model.ResBody;
  10. import cn.com.qmth.examcloud.app.model.Result;
  11. import okhttp3.Request;
  12. import okhttp3.Response;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. public class HttpUtils {
  16. private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
  17. public static Result<String> call(Request request) throws Exception {
  18. Response response = HttpBuilder.client.getInstance().newCall(request).execute();
  19. String bodyStr = response.body().string();
  20. if (response.isSuccessful()) {
  21. return new Result().success(bodyStr);
  22. } else {
  23. log.warn("Http response is " + bodyStr);
  24. ResBody body = new JsonMapper().fromJson(bodyStr, ResBody.class);
  25. if (body != null && body.getCode() != null) {
  26. if (Constants.CODE_403.equals(body.getCode())) {
  27. return new Result().noAuthError();
  28. }
  29. if (Constants.CODE_404.equals(body.getCode())) {
  30. return new Result().noFoundError();
  31. }
  32. if (Constants.CODE_0.equals(body.getCode())) {
  33. return new Result().error(body.getErrorMsg());
  34. }
  35. return new Result().error(body.getDesc());
  36. }
  37. return new Result().error(bodyStr);
  38. }
  39. }
  40. }