首先请求第三方接口的方法有很多,我这里使用的是hutool对原生http请求的一个封装的方法,具体使用如下。
1.添加pom文件依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>
2.根据接口文档的返回值封装实体类
@Data
public class Result implements Serializable {
private static final long serialVersionUID = -3948389268046368059L;
private Integer code;
private String msg;
private Object data;
public Result() {}
public Result(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static Result success() {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
return result;
}
public static Result success(Object data) {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
result.setData(data);
return result;
}
public static Result failure(ResultCode resultCode) {
Result result = new Result();
result.setResultCode(resultCode);
return result;
}
public static Result failure(ResultCode resultCode, Object data) {
Result result = new Result();
result.setResultCode(resultCode);
result.setData(data);
return result;
}
public void setResultCode(ResultCode code) {
this.code = code.code();
this.msg = code.message();
}
}
//下面这个是状态码code的枚举类
public enum ResultCode {
/* 成功状态码 */
SUCCESS(0, "success"),
/* 参数错误:10001-19999 */
PARAM_IS_INVALID(10001, "参数无效"),
PARAM_IS_BLANK(10002, "参数为空"),
PARAM_TYPE_BIND_ERROR(10003, "参数类型错误"),
PARAM_NOT_COMPLETE(10004, "参数缺失"),
/* 用户错误:20001-29999*/
USER_NOT_LOGGED_IN(20001, "用户未登录"),
USER_LOGIN_ERROR(20002, "账号不存在或密码错误"),
USER_ACCOUNT_FORBIDDEN(20003, "账号已被禁用"),
USER_NOT_EXIST(20004, "用户不存在"),
USER_HAS_EXISTED(20005, "用户已存在"),
/* 业务错误:30001-39999 */
SPECIFIED_QUESTIONED_USER_NOT_EXIST(30001, "某业务出现问题"),
/* 系统错误:40001-49999 */
SYSTEM_INNER_ERROR(40001, "系统繁忙,请稍后重试"),
/* 数据错误:50001-599999 */
RESULE_DATA_NONE(50001, "数据未找到"),
DATA_IS_WRONG(50002, "数据有误"),
DATA_ALREADY_EXISTED(50003, "数据已存在"),
/* 接口错误:60001-69999 */
INTERFACE_INNER_INVOKE_ERROR(60001, "内部系统接口调用异常"),
INTERFACE_OUTTER_INVOKE_ERROR(60002, "外部系统接口调用异常"),
INTERFACE_FORBID_VISIT(60003, "该接口禁止访问"),
INTERFACE_ADDRESS_INVALID(60004, "接口地址无效"),
INTERFACE_REQUEST_TIMEOUT(60005, "接口请求超时"),
INTERFACE_EXCEED_LOAD(60006, "接口负载过高"),
/* 权限错误:70001-79999 */
PERMISSION_NO_ACCESS(70001, "无访问权限");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
public static String getMessage(String name) {
for (ResultCode item : ResultCode.values()) {
if (item.name().equals(name)) {
return item.message;
}
}
return name;
}
public static Integer getCode(String name) {
for (ResultCode item : ResultCode.values()) {
if (item.name().equals(name)) {
return item.code;
}
}
return null;
}
@Override
public String toString() {
return this.name();
}
}
3.开始编写我们的两个请求的格式get 与 post ,我这边因为一开始接口不同需要测试代码所以写了两个post的格式,一种是请求格式为表单的一种是json的。你们看自己需求分别拿就可以
@Slf4j
public class RestFulUtil {
/**
* @param c 需要转换的实体类
* @param pathUrl 需要请求的接口路径
* @param body 请求的参数
*/
public static <T> T doPostJSON(Class<T> c, String pathUrl, String body) {
HttpResponse execute = HttpRequest.post(pathUrl)
.headerMap(getJsonCommonHeader(), true) //请求的消息头
.timeout(5)//请求超时时间
.body(body)//请求的json格式的参数
.execute();
int status = execute.getStatus();
if (200 == status || 201 == status) {
String respBody = execute.body();//请求参数后的返回值
T bean = JSONUtil.toBean(respBody, c);//将返回的数据转成自己的实体类
return bean;
} else {
log.error("请求url:{}, 请求体:{}, 请求头:{}, 响应码异常:{},响应体:{}");
}
return null;
}
/**
* @param c 需要转换的实体类
* @param pathUrl 需要请求的接口路径
* @param formMap 请求的参数
*/
public static <T> T doPostForm(Class<T> c, String pathUrl, Map<String, Object> formMap) {
HttpResponse execute = HttpRequest.post(pathUrl)
.headerMap(getCommonHeader(), true)
.timeout(3000)
.form(formMap)
.execute();
int status = execute.getStatus();
if (200 == status || 201 == status) {
String respBody = execute.body();
T bean = JSONUtil.toBean(respBody, c);
return bean;
} else {
log.error("请求url:{}, 请求体:{}, 请求头:{}, 响应码异常:{},响应体:{}", pathUrl, formMap, getCommonHeader(), status, execute);
}
return null;
}
/**
* @param c 需要转换的实体类
* @param pathUrl 需要请求的接口路径
* @param headerMap 请求头的token
* */
public static <T> T doGetT(Class<T> c, String pathUrl, Map<String, String> headerMap) {
HttpResponse execute = HttpRequest.get(pathUrl)
.headerMap(getCommonHeader(), true)
.headerMap(headerMap, true)
.timeout(3000)
.execute();
System.out.println(execute.body());
int status = execute.getStatus();
if (200 == status || 201 == status) {
String respBody = execute.body();
T bean = JSONUtil.toBean(respBody, c);
return bean;
} else {
log.error("请求url:{}, 请求体:{}, 请求头:{}, 响应码异常:{},响应体:{}");
}
return null;
}
//这个方法是表单格式的请求头的一些参数
private static Map<String, String> getCommonHeader() {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("accept", "*/*");
headerMap.put("connection", "Keep-Alive"); //维持长链接
return headerMap;
}
//json格式的请求头
private static Map<String, String> getJsonCommonHeader() {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("accept", "*/*");
headerMap.put("connection", "Keep-Alive"); //维持长链接
headerMap.put("Content-Type", "application/json;charset=utf-8");
return headerMap;
}
}
4.开始对接口进行请求(只是一个简单的登录的一个简单的请求接口,其他的接口以此类推即可)
public class GetToken {
/**
* 获取token
*/
public static Map<String,String> getToken() throws IllegalAccessException {
Map<String, String> m = new HashMap<>();
m.put("username", "admin");
m.put("password", "123456");
Result result = RestFulUtil.doPostJSON( Result.class, "https://localhost:1234/hello/#/login", JSON.toJSONString(m));
if (result.getCode() == 0) {
JSONObject data = JSONObject.parseObject(result.getData().toString());
String t = (String) data.get("authorization");
Map<String, String> token = new HashMap<>();
token.put("token", t);
return token;
}else {
return new HashMap<>();
}
}
}