@Slf4j
public abstract class AbstractThemeLinkInvoker<R, T> {
@Autowired
ExceptionManager exceptionManager;
@Autowired
HttpInvokerTemplate httpInvoker;
private static final Integer SUCCESS_CODE = 0;
@HeraclesDynamicConfig(key = "theme.link.api.host", fileName = "thirdparty.properties", textType = TextType.NORMAL)
private String themeLinkApiHost;
@Tracing
public ThemeLinkCommonResp<T> invoke(R request) {
String url = themeLinkApiHost + getUrl();
Map<String, String> params = JSONObject.parseObject(JSONObject.toJSONString(request), Map.class);
ThemeLinkCommonResp<T> response = httpInvoker.requestFormByPost(url, params,
new TypeReference<ThemeLinkCommonResp<T>>(getDataClass()) { });
checkSuccess(response);
return response;
}
private void checkSuccess(ThemeLinkCommonResp response) {
if (Objects.nonNull(response) && SUCCESS_CODE.equals(response.getErrno())) {
return;
}
throw exceptionManager.createException(ResponseCode.SYSTEM_ERROR, "操作失败,请稍后再试");
}
protected abstract String getUrl();
protected abstract Class<T> getDataClass();
}
其中http调用的代码为
public <T> T requestFormByPost(String url, Map<String, String> request, TypeReference<T> typeReference) {
Map<String, String> headers = Maps.newHashMap();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
byte[] responseBytes = null;
try {
responseBytes = HttpConnectUtil
.getResponseByPost(HttpConnectManager.newHttpClient(connectionTimeout, readTimeout), url, headers,
request);
} catch (HttpStatusCodeException e) {
log.error("Req {} {} {} RespStatus {}, response = {}", url, headers, request, e.getHttpCode(),
responseBytes != null ? new String(responseBytes) : "", e);
throw new RuntimeException("IllegalStatus " + e.getHttpCode());
} catch (Exception e) {
log.error("HttpReqError {} {} {}", url, headers, request, e);
throw new RuntimeException(e);
}
String responseBodyString = new String(responseBytes);
log.debug("responseBodyString={}" + responseBodyString);
return JSON.parseObject(responseBodyString, typeReference);
}
某个继承类
@Slf4j
@Component
public class ThemeLinkContentListInvoker extends
AbstractThemeLinkInvoker<ThemeLinkContentListRequest, ThemeLinkContentListResponse> {
@Override
public String getUrl() {
return "/xxxx";
}
@Override
public Class<ThemeLinkContentListResponse> getDataClass() {
return ThemeLinkContentListResponse.class;
}
}
返回公共类
@Data
@ToString
public class ThemeLinkCommonResp<T> {
private Integer errno;
private T data;
}