这里是用的自己封装的工具包,也可以直接用RestTemplate。
案例1:参数多时,可以封装一个类
controller:
@ApiOperation(httpMethod = "POST", value = "新增/更新课程 随堂练习题")
@RequestMapping("/addOrEditContentQuestion")
// 参数过多的话,可以定义一个类 ContentQuestionAddParams
public Result<String> addOrEditContentQuestion(@Validated @RequestBody ContentQuestionAddParams question) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
Result<String> result = new Result<>();
YunApiResult<String> res = courseYunService.addOrEditContentQuestion(question);
result.setData(res.getData());
result.setCode(res.getStatus());
result.setMsg(res.getError_desc());
return result;
}
参数 ContentQuestionAddParams 类:
@ApiModel(value="ContentQuestionAddParams",description="新增课程随堂练习试题参数")
@SuppressWarnings("serial")
public class ContentQuestionAddParams implements Serializable {
@NotNull
@ApiModelProperty(value="选项数据,添加单选题和多选题时必填,示例:{\"A\":\"A选项\",\"B\":\"B选项\"}")
private Map<String,String> choiceData;
@NotBlank(message = "试题id不能为空", groups = {UpdateValidGroup.class})
@ApiModelProperty(value="试题id")
private String id;
public ContentQuestionAddParams(){}
public Map<String, String> getChoiceData() {
return choiceData;
}
public void setChoiceData(Map<String, String> choiceData) {
this.choiceData = choiceData;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
service:
public YunApiResult<String> addOrEditContentQuestion(ContentQuestionAddParams question) throws InvocationTargetException, IllegalAccessException, IntrospectionException {
String url = ResourcesConfig.getCourseInterfaceUrl() + "/api/question/addOrEditQuestion";
// 把实体类转为Map形式,这样参数就是map形式传递
Map<String,Object> params = MapUtils.convertBean(question);
// 特殊类型进行转换
String choiceData = JSON.toJSONString(params.get("choiceData"));
params.put("choiceData",choiceData);
// 发送请求,并拿到结果str
String str = restHttpTemplate.sendPost(url, new ParameterizedTypeReference<String>() {}, params);
YunApiResult<String> result = JSON.parseObject(str,new TypeReference<YunApiResult<String>>() {});
return result;
}
案例2:参数较少时:
controller
@ApiOperation(httpMethod = "GET", value = "查询章节下的试题列表")
@ApiImplicitParams({@ApiImplicitParam(name = "sectionId", value = "章节id", dataType = "String", required = true, paramType = "query"),
@ApiImplicitParam(name = "timePoint", value = "章节时间点,不必填", dataType = "String", paramType = "query")})
@RequestMapping("/listQuestionBySectionId")
public Result<List<ContentQuestionVo>> listQuestionBySectionId( @RequestParam String sectionId, String timePoint) {
Result<List<ContentQuestionVo>> result = new Result<>();
YunApiResult<List<ContentQuestionVo>> res = courseYunService.listQuestionBySectionId(sectionId , timePoint);
result.setData(res.getData());
result.setCode(res.getStatus());
result.setMsg(res.getError_desc());
return result;
}
service
public YunApiResult<List<ContentQuestionVo>> listQuestionBySectionId(String sectionId, String timePoint) {
String url = ResourcesConfig.getCourseInterfaceUrl() + "/api/question/listQuestionBySectionId";
Map<String,Object> params = new HashMap<>();
params.put("sectionId",sectionId);
params.put("timePoint",timePoint);
String str = restHttpTemplate.sendGet(url, new ParameterizedTypeReference<String>() {}, params);
YunApiResult<List<ContentQuestionVo>> result = JSON.parseObject(str,new TypeReference<YunApiResult<List<ContentQuestionVo>>>() {});
return result;
}
工具类:
/**
* 发送http请求 GET、POST、PUT、Delete
*/
@Component
public class RestHttpTemplate {
private RestTemplate restTemplate;
public RestTemplate getRestTemplate() {
if (restTemplate == null) {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create()
.setMaxConnTotal(1000)
.setMaxConnPerRoute(500)
.build());
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
restTemplate = new RestTemplate(httpRequestFactory);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
return restTemplate;
}
/***
* 发送get请求
* @param url 请求的url地址 不允许包含?以及?后的参数
* @param responseType 请求返回的实体类型
* @param map 请求参数集合 自动封装参数进url
* @return T
*/
public <T> T sendGet(String url, Class<T> responseType, Map<String, Object> map) {
url = handleParamMap(url, map);
if (map == null) {
map = new HashMap<>(2);
}
T t = getRestTemplate().getForObject(url, responseType, map);
return t;
}
/**
* 发送 http get
* @param url url地址
* @param parameterizedTypeReference ParameterizedTypeReference
* @param map 参数map集合
* @param <T> T
* @return T
*/
public <T> T sendGet(String url, ParameterizedTypeReference<T> parameterizedTypeReference, Map<String, Object> map) {
url = handleParamMap(url, map);
if (map == null) {
map = new HashMap<>(2);
}
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<T> resp = getRestTemplate().exchange(url, HttpMethod.GET, requestEntity,
parameterizedTypeReference, (Map) map);
return resp.getBody();
}
private String handleParamMap(String url, Map<String, Object> map) {
StringBuilder urlBuilder = new StringBuilder(16);
if (map != null) {
boolean first = true;
Iterator var5 = ((Map) map).entrySet().iterator();
while (var5.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry) var5.next();
if (entry.getValue() != null) {
if (first) {
urlBuilder.append(entry.getKey()).append("={").append(entry.getKey()).append("}");
first = false;
} else {
urlBuilder.append("&").append(entry.getKey()).append("={").append(entry.getKey()).append("}");
}
}
}
url = url + "?" + urlBuilder.toString();
}
return url;
}
/***
* 发送 http delete
* @param url 请求的url地址 不允许包含?以及?后的参数
* @param responseType 请求返回的实体类型
* @param map 请求参数集合 自动封装参数进url
* @return T
*/
public <T> T sendDelete(String url, Class<T> responseType, Map<String, Object> map) {
if (map != null) {
url += "?";
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null) {
url += entry.getKey() + "=" + entry.getValue() + "&";
}
}
}
ResponseEntity<T> entity = getRestTemplate().exchange(url, HttpMethod.DELETE, null, responseType);
T t = entity.getBody();
return t;
}
/***
* 发送 http post
* @param url url地址
* @param responseType 类型
* @param map 参数map
* @param <T> T
* @return T
*/
public <T> T sendPost(String url, Class<T> responseType, Map<String, Object> map) {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null) {
postParameters.add(entry.getKey(), entry.getValue());
}
}
}
T t = getRestTemplate().postForObject(url, postParameters, responseType);
return t;
}
/**
* 发送 http put
* @param url url地址
* @param parameterizedTypeReference ParameterizedTypeReference
* @param map 参数map集合
* @param <T> T
* @return T
*/
public <T> T sendPut(String url, ParameterizedTypeReference<T> parameterizedTypeReference, Map<String, Object> map) {
if (map == null) {
map = new HashMap<>(2);
}
MultiValueMap<String, Object> formData = getParamData(map);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
ResponseEntity<T> resp = this.getRestTemplate().exchange(url, HttpMethod.PUT, requestEntity, parameterizedTypeReference);
return resp.getBody();
}
/**
* 发送 http post
* @param url url地址
* @param parameterizedTypeReference ParameterizedTypeReference
* @param map 参数map集合
* @param <T> T
* @return T
*/
public <T> T sendPost(String url, ParameterizedTypeReference<T> parameterizedTypeReference, Map<String, Object> map) {
if (map == null) {
map = new HashMap<>(2);
}
MultiValueMap<String, Object> formData = getParamData(map);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
ResponseEntity<T> resp = this.getRestTemplate().exchange(url, HttpMethod.POST, requestEntity, parameterizedTypeReference);
return resp.getBody();
}
private MultiValueMap<String, Object> getParamData(Map<String, Object> map) {
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
formData.add(entry.getKey(), entry.getValue());
}
return formData;
}
/**
* 发送 http delete
* @param url url地址
* @param parameterizedTypeReference ParameterizedTypeReference
* @param map 参数map集合
* @param <T> T
* @return T
*/
public <T> T sendDelete(String url, ParameterizedTypeReference<T> parameterizedTypeReference, Map<String, Object> map) {
if (map == null) {
map = new HashMap<>(2);
}
MultiValueMap<String, Object> formData = getParamData(map);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
ResponseEntity<T> resp = this.getRestTemplate().exchange(url, HttpMethod.DELETE, requestEntity, parameterizedTypeReference);
return resp.getBody();
}
/**
* 发送 http put
* @param url url地址
* @param responseType responseType
* @param map 参数map地址
* @param <T> T
* @return T
*/
public <T> T sendPut(String url, Class<T> responseType, Map<String, Object> map) {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap();
if (map != null) {
Iterator var5 = map.entrySet().iterator();
while (var5.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry) var5.next();
if (entry.getValue() != null) {
postParameters.add(entry.getKey(), entry.getValue().toString());
}
}
}
HttpEntity entity = new HttpEntity(postParameters, postParameters);
ResponseEntity<T> info = this.getRestTemplate().exchange(url, HttpMethod.PUT, entity, responseType, new Object[0]);
return info.getBody();
}
public static void main(String[] args) {
RestHttpTemplate restHttpTemplate = new RestHttpTemplate();
String url = "http://localhost:9080/yunapi/teachers/";
Map<String, Object> params = new HashMap<>(16);
params.put("name", "李四");
params.put("platformId", "7");
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {
};
//测试post
String s1 = restHttpTemplate.sendPost(url, String.class, params);
String s2 = restHttpTemplate.sendPost(url, reference, params);
System.out.println(s1);
}
}