RestTemplateget请求多参数简单封装
使⽤RestTemplate发送get请求时,如果有多个参数拼接起来会⽐较⿇烦,在此做个简单的封装
public static void main(String[] args) {
Map<String, Object> paramMap = new HashMap<>(16);
paramMap.put("userId", "8a0bb0a698c142420198c15a7e5b0001");
paramMap.put("pageNum", "1");
paramMap.put("pageSize", "3");
paramMap.put("createStartTime", "2029-08-09");
paramMap.put("createEndTime", null);
//获取积分明细
ObjectDataResponse objectDataResponse = getForObject("10.200.40.157:8180/manage/scoreDetail", paramMap);
System.out.println(objectDataResponse);
}
/**
* 封装的get请求,暂时只⽀持map传参,并且value只⽀持基本类型和String
*
* @param url
* @param object
* @return
*/
private static ObjectDataResponse getForObject(String url, Object object) {
StringBuffer stringBuffer = new StringBuffer(url);
if (object instanceof Map) {
spring framework runtime
Iterator iterator = ((Map) object).entrySet().iterator();
if (iterator.hasNext()) {
stringBuffer.append("?");
Object element;
while (iterator.hasNext()) {
element = ();
Map.Entry<String, Object> entry = (Map.Entry) element;
//过滤value为null,value为null时进⾏拼接字符串会变成 "null"字符串
if (Value() != null) {
stringBuffer.append(element).append("&");
}
url = stringBuffer.substring(0, stringBuffer.length() - 1);
}
}
} else {
throw new RuntimeException("url请求:" + url + "请求参数有误不是map类型");
}
log.info("url请求:" + url);
return new RestTemplate().getForObject(url, ObjectDataResponse.class);
}
请求结果
16:31:08.803 [main] INFO com.smf.interfaces.ManagementController - url请求:10.200.40.157:8180/manage/scoreDetail?createStartTime=2029-08-09&pageSize=10&userId=8a0bb0a698c142420198c15a7e5b0001&pageNum=1
16:31:09.208 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "10.200.40.157:8180/manage/scoreDetail?createStartTime=2029-08-09&pageSize=10&userId=8a0bb0a698c142420198c15a7e5b0001&pa 16:31:09.271 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
16:31:09.834 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "10.200.40.157:8180/manage/scoreDetail?createStartTime=2029-08-09&pageSize=10&userId=8a0bb0a698c142420198c15a7e5b0001&pageNum= 16:31:09.835 [main] DEBUG org.springframework.web.client.RestTemplate - Reading [class sponse.ObjectDataResponse] as "application/json;charset=UTF-8" using [org.verter.json.MappingJackson2H ObjectDataResponse(super=RestfulResponse(super=sponse.ObjectDataResponse@76b92ca8, code=20000, msg=成功), data={pageNum=1, pageSize=10, total=3, totalPage=1, rows=[{createTime=
2037.12.06 02:55:38, num=1

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。