Springboot HTTP请求,Springboot HTTP 请求 Demo。Get/Post
今天做了在做年会活动项目的时候,为了增加了一个语义分析,项目是 Springboot 搭建的,那么 Springboot 我记得是有 HTTP 请求的轮子,那么就不造了,直接使用,这里就分享一下。
Rest HTTP请求~RestTemplate
RestTemplate 主要是用来做 Rest
请求,所以是RestClient
。下面的 Demo 是用来做一个普通的 HTTP 请求。
直接上代码了:
log.debug("语义分析调用开始");
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
//设置超时时间,请求时间,连接时间,读取时间,都是1秒,这里都是用静态变量
httpRequestFactory.setConnectionRequestTimeout(Constant.I1000);
httpRequestFactory.setConnectTimeout(Constant.I1000);
httpRequestFactory.setReadTimeout(Constant.I1000);
//获取对话
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
HttpHeaders headers = new HttpHeaders();
//JSON contentType
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//我们发起 HTTP 请求还是最好加上"Connection","close" ,有利于程序的健壮性
headers.set("Connection","close");
HttpEntity<String> requestEntity = new HttpEntity<>(content, headers);
ResponseEntity<String> response;
try {
//发起请求
response = restTemplate.exchange(String.format(Constant.LEXICON_URL,URLEncoder.encode(content, Constant.UTF_8)),
HttpMethod.GET,//get
requestEntity,
String.class);
//获取返回值
String resTxt = response.getBody();
if(isNotBlank(resTxt)){
Map<String,Object> map = new Gson().fromJson(resTxt,Map.class);
/**
* 返回值
* {"result":0,"content":"曲项向天歌"}
* result 在反转对象的时候,会变成 Double 类型,是0.0
*/
if(Constant.D0.equals(map.get("result"))){
//获取返回值
content = (String) map.get("content");
//判断返回值是否有{br},替换成 \n
if(isNotBlank(content) && contains(content,"{br}")){
content = infoFilter(content.replaceAll("\\{br\\}","\n"));
}
}
}
dto.setContent(content);
log.debug("语义分析调用结束");
} catch (RestClientException e) {
throw e;
}
常量池:
Integer I1000 = new Integer(1000);
Double D0 = new Double(0.0);
String UTF_8 = "utf-8";
String LEXICON_URL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s";
String LEXICON_MARK = "!!(";
语义分析API 介绍
API地址:http://api.qingyunke.com/
智能机器人API接口说明
支持功能:天气、翻译、藏头诗、笑话、歌词、计算、域名信息/备案/收录查询、IP查询、手机号码归属、人工智能聊天
接口地址:http://api.qingyunke.com/api.php?key=free&appid=0&msg=关键词
key 固定参数free
appid 设置为0,表示智能识别,可忽略此参数
msg 关键词,请参考下方参数示例,该参数可智能识别,该值请经过 urlencode 处理后再提交
返回结果:{"result":0,"content":"内容"}
result
状态,0表示正常,其它数字表示错误
content
信息内容,中文请做 urlencode
温馨提示:本API完全免费使用(建议频率控制在1000次/1小时以内),我们将尽可能提供最快最稳定的免费服务器
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/273.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。