package me.zhengjie.modules.api; import com.alibaba.fastjson.JSONObject; import me.zhengjie.exception.BadRequestException; import me.zhengjie.utils.HttpUtil; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import java.util.Map; @Component public class Api { public Object get(String getUrl, Map getParams) { // 发起通信 ResponseEntity strRes = HttpUtil.get(getUrl, getParams, new HttpHeaders(), String.class); // 通信结构 JSONObject objBody = JSONObject.parseObject(strRes.getBody()); // 结果集 return recordSet(objBody); } public Object post(String postUrl, Map postParams) { // 发起通信 ResponseEntity strRes = HttpUtil.post(postUrl, postParams, new HttpHeaders(), String.class); // 通信结构 JSONObject objBody = JSONObject.parseObject(strRes.getBody()); // 结果集 return recordSet(objBody); } private Object recordSet(JSONObject objBody) { // 判断通信错误码 if (objBody != null && objBody.get("msg") != null) { // 错误信息 throw new BadRequestException(objBody.get("msg").toString()); } else if (objBody != null && objBody.get("result") != null) { // 通信结果 return objBody.get("result"); } else { // 通信结果 return null; } } }