调用实例
废话不多说,直接看代码
Page page = new Page();
page.setPageNum(1);
page.setPageSize(1);
Map<String, Object> params =new HashMap();
params.put("ids", ids);
params.put("page", page);
JSONObject jsonObj=new JSONObject(params);//请求参数
HttpResponse result2 = HttpRequest.post(接口地址).header("appId", appId).header("accessToken", accessToken)
.body(jsonObj.toString()).contentType("application/json") .execute();
附上工具类,自行下载相关jar包
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONTokener;
import cn.hutool.json.JSONUtil;
public class HttpRequestUtils {
private static final String REQUEST_TYPE_GET="GET";
private static final String REQUEST_TYPE_POST="POST";
private static final String ENCODING="UTF-8";
/**
* 调用接口测试,返回接口请求集
* @param requestVo
* @return
* @throws Exception
*/
public static Object interfaceRequest(String url,String type,Map<String,Object> head,Map<String,Object> params,String encoding)throws Exception{
Console.log("[ 接口请求方法调用 ]");
String jsonStr = null;
HttpRequest request =null;
HttpResponse response =null;
//判定是get请求还是post请求
if (REQUEST_TYPE_GET.equalsIgnoreCase(type)){
request = HttpRequest.get(url);
}else if(REQUEST_TYPE_POST.equalsIgnoreCase(type)){
request = HttpRequest.post(url);
}
//拼接请求头
if(ObjectUtil.isNotNull(head)){
for (String keys : head.keySet()) {
request.header(keys,head.get(keys).toString());
}
}
//请求编码格式
request.charset(StringUtils.isBlank(encoding)?ENCODING:encoding);
//传递参数,并执行请求获取返回值
if (REQUEST_TYPE_GET.equalsIgnoreCase(type)){
response= request.form(params).execute();
}else if(REQUEST_TYPE_POST.equalsIgnoreCase(type)){
response = request.body(JSONUtil.parseFromMap(params)).execute();
}
if(response.getStatus()==200){
jsonStr=response.body();
}else{
jsonStr="REQUEST ERROR : "+response.getStatus();
}
Console.error("[{} 接口{} 返回值{}]",type,url,jsonStr);
//将空值null转换为String类型的"null"
jsonStr=jsonStr.replaceAll(":null,",":\"null\",");
jsonStr=jsonStr.replaceAll(":null}",":\"null\"}");
//判定是否为json字符串
if(JSONUtil.isJson(jsonStr)){
Object json = new JSONTokener(jsonStr).nextValue();
if(json instanceof JSONObject){
return json;
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
return jsonArray;
}
}
return jsonStr;
}
}