天气GET调用
public class MessageUtil {
public static void main(String[] args) throws Exception {
Random random = new Random();
String code = "#code#=";
for (int i = 0;i < 6;i++){
code+=random.nextInt(10);
}
System.out.println(code);
String myurl = "http://v.juhe.cn/sms/send?mobile=18233545556&tpl_id=194894&tpl_value="+ URLEncoder.encode(code,"utf-8") +"&key=1b46cef759c9bf970ce5a15ded0b4c37";
String result =getUrl(myurl);
System.out.println(result);
}
//Java发送HTTP的get请求
public static String getUrl(String myurl){
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // 设置该连接是可以输出的
connection.setRequestMethod("GET"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) { // 读取数据
result.append(line + "\n");
}
connection.disconnect();
//System.out.println(result.toString());
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
运动搜索接口提供
@Controller
@RequestMapping("/api/article")
public class SuperarticleController {
@Resource
private SuperarticleService superarticleService;
//总接口测试
@RequestMapping("/test")
@ResponseBody
public List<Superarticle> selectAll(){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey(null);
return superarticles;
}
//热词接口
@RequestMapping("/search/hotkey")
@ResponseBody
public ResultVo<Map<Integer,String>> selectHotKey(){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey(null);
Map<Integer,String> map = new HashMap<>();
Set<String> set = new HashSet<>();
int i = 0;
for (Superarticle superarticle : superarticles) {
String sakeys = superarticle.getSakeys();
String sasort = superarticle.getSasort();
set.add(sakeys);
set.add(sasort);
}
for (String key : set) {
map.put(i,key);
i+=1;
}
if (!StringUtils.isEmpty(superarticles)) {
return new SuperArticleVoUtils<>().success3(map);
}else {
return new SuperArticleVoUtils<>().error3();
}
}
//运动养成接口
@RequestMapping("/list/develop")
@ResponseBody
public ResultVo findDevelopArticle(){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey("运动养成");
List list = new LinkedList<>();
for (Superarticle superarticle : superarticles) {
Map<Object, Object> map = new HashMap<>();
map.put("title",superarticle.getSatitle());
map.put("imgurl",superarticle.getSaimgurl());
map.put("imgurl2",superarticle.getSaimgurl2());
map.put("imgurl3",superarticle.getSaimgurl3());
map.put("content",superarticle.getSacontent());
map.put("sort",superarticle.getSasort());
map.put("partid",superarticle.getSapartid());
List<Article> articleList = superarticle.getArticleList();
List newarticleList = new LinkedList();
for (Article article : articleList) {
ArticleListDTO listDTO = new ArticleListDTO();
listDTO.setLittleTitle(article.getAtitle());
listDTO.setLittleContent(article.getAdetail());
listDTO.setLittleImgurl(article.getAimgurl());
newarticleList.add(listDTO);
}
map.put("developlist",newarticleList);
list.add(map);
}
if (!StringUtils.isEmpty(superarticles)){
return new SuperArticleVoUtils<>().success1(list);
}else {
return new SuperArticleVoUtils<>().error1();
}
}
//健康轻食接口
@RequestMapping("/list/health")
@ResponseBody
public ResultVo findHealthArticle(){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey("健康轻食");
List list = new LinkedList<>();
for (Superarticle superarticle : superarticles) {
Map<Object, Object> map = new HashMap<>();
map.put("title",superarticle.getSatitle());
map.put("imgurl",superarticle.getSaimgurl());
map.put("imgurl2",superarticle.getSaimgurl2());
map.put("imgurl3",superarticle.getSaimgurl3());
map.put("content",superarticle.getSacontent());
map.put("sort",superarticle.getSasort());
map.put("partid",superarticle.getSapartid());
List<Article> articleList = superarticle.getArticleList();
List newarticleList = new LinkedList();
for (Article article : articleList) {
ArticleListDTO listDTO = new ArticleListDTO();
listDTO.setLittleTitle(article.getAtitle());
listDTO.setLittleContent(article.getAdetail());
listDTO.setLittleImgurl(article.getAimgurl());
newarticleList.add(listDTO);
}
map.put("healthlist",newarticleList);
list.add(map);
}
if (!StringUtils.isEmpty(superarticles)){
return new SuperArticleVoUtils<>().success2(list);
}else {
return new SuperArticleVoUtils<>().error2();
}
}
//搜索运动相关
@RequestMapping("/search/about")
@ResponseBody
public ResultVo searchAboutArticle(@RequestParam(name = "key",defaultValue = "运动") String key){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey(key);
List list = new LinkedList<>();
for (Superarticle superarticle : superarticles) {
Map<Object, Object> map = new HashMap<>();
map.put("title",superarticle.getSatitle());
map.put("imgurl",superarticle.getSaimgurl());
map.put("imgurl2",superarticle.getSaimgurl2());
map.put("imgurl3",superarticle.getSaimgurl3());
map.put("content",superarticle.getSacontent());
map.put("sort",superarticle.getSasort());
map.put("partid",superarticle.getSapartid());
List<Article> articleList = superarticle.getArticleList();
List newarticleList = new LinkedList();
for (Article article : articleList) {
ArticleListDTO listDTO = new ArticleListDTO();
listDTO.setLittleTitle(article.getAtitle());
listDTO.setLittleContent(article.getAdetail());
listDTO.setLittleImgurl(article.getAimgurl());
newarticleList.add(listDTO);
}
map.put("aboutsearchlist",newarticleList);
list.add(map);
}
if (!StringUtils.isEmpty(superarticles)){
return new SuperArticleVoUtils<>().success4(list);
}else {
return new SuperArticleVoUtils<>().error4();
}
}
//搜索健康轻食
@RequestMapping("/search/health")
@ResponseBody
public ResultVo searchHealthArticle(@RequestParam(name = "key",defaultValue = "健康") String key){
List<Superarticle> superarticles = superarticleService.selectAllSuperArticleByKey(key);
List list = new LinkedList<>();
for (Superarticle superarticle : superarticles) {
Map<Object, Object> map = new HashMap<>();
map.put("title",superarticle.getSatitle());
map.put("imgurl",superarticle.getSaimgurl());
map.put("imgurl2",superarticle.getSaimgurl2());
map.put("imgurl3",superarticle.getSaimgurl3());
map.put("content",superarticle.getSacontent());
map.put("sort",superarticle.getSasort());
map.put("partid",superarticle.getSapartid());
List<Article> articleList = superarticle.getArticleList();
List newarticleList = new LinkedList();
for (Article article : articleList) {
ArticleListDTO listDTO = new ArticleListDTO();
listDTO.setLittleTitle(article.getAtitle());
listDTO.setLittleContent(article.getAdetail());
listDTO.setLittleImgurl(article.getAimgurl());
newarticleList.add(listDTO);
}
map.put("healthsearchlist",newarticleList);
list.add(map);
}
if (!StringUtils.isEmpty(superarticles)){
return new SuperArticleVoUtils<>().success5(list);
}else {
return new SuperArticleVoUtils<>().error5();
}
}
}
HttpUtil.java
public class HttpUtil {
/**
* 一般情况下,我们对外发送请求的方式是固定的,不会说一会 get 一会 post,只不过是因为我们这个是封装的方法,可能不仅仅是给推送状态报告用
* 如果是用做推送状态报告,那么发送的数据格式和返回的数据格式都是我们说的算
* @param url
* @param paramsMap
* @param method
* @return
*/
public static String sendRequest(String url, Map<String, Object> paramsMap,String method) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();//获取用于网络请求的客户端
CloseableHttpResponse response = null;
if ("get".equalsIgnoreCase(method)) {
String execUrl = joinParams(url, paramsMap);//拼接请求地址
HttpGet httpGet=new HttpGet(execUrl);
RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
httpGet.setConfig(config);
try {
response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();//获取响应状态行
int statusCode = statusLine.getStatusCode();//获取状态码,如 200 404 等
if (statusCode == 200) {
HttpEntity responseEntity = response.getEntity();//获取响应正文
return EntityUtils.toString(responseEntity);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 拼接get 请求的参数
* @param url
* @param paramsMap
* @return
*/
public static String joinParams(String url, Map<String, Object> paramsMap) {
if (paramsMap == null || paramsMap.size() == 0) {
//没有参数
return url;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(url).append("?");
Set<Map.Entry<String, Object>> set = paramsMap.entrySet();
// for (Map.Entry<String, Object> entry : set) {
// String key = entry.getKey();
// Object value = entry.getValue();
// if (key == null) {
// continue;//如果 key 是空的就略过当前参数
// }
// //我们的参数第一个是直接拼在?后的,但是如果有好几个参数,第二个开始开头拼&
// //遍历 set 的话如何知道当前是第一个参数
// stringBuilder.append("&").append(key).append("=").append(value);
// }
// stringBuilder.delete(0, 1);//删除最前面的&
int count = 0;
for (Map.Entry<String, Object> entry : set) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;//如果 key 是空的就略过当前参数
}
//我们的参数第一个是直接拼在?后的,但是如果有好几个参数,第二个开始开头拼&
//遍历 set 的话如何知道当前是第一个参数
if (count==0) {
stringBuilder.append(key).append("=").append(value);
}else{
stringBuilder.append("&").append(key).append("=").append(value);
}
count++;
}
return stringBuilder.toString();
}
}
发送报告
@Service
public class PushStatusReportServiceImpl implements PushStatusReportService {
@Autowired
private CacheService cacheService;
@Override
public void sendReport(Standard_Report report) {
//获取到用户的回调地址
Map map = cacheService.hmget(CacheConstants.CACHE_PREFIX_CLIENT + report.getClientID());
if (map != null&&map.size()>0) {
String receivestatusurl = (String) map.get("receivestatusurl");//获取回调地址
//发起请求,传递我们的结果
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("srcId", report.getSrcID());
paramsMap.put("mobile", report.getMobile());
paramsMap.put("state", report.getState());
paramsMap.put("errorCode", report.getErrorCode());
String result = HttpUtil.sendRequest(receivestatusurl, paramsMap, "get");
System.err.println("返回结果:"+result);
}
}
}
MQ触发
@Component
public class ReceiveFromMQListener {
@Autowired
private PushStatusReportService statusReportService;
@RabbitListener(queues = RabbitMqConsants.TOPIC_PUSH_SMS_REPORT, containerFactory = "taskContainerFactory")
public void onMessage(Standard_Report report) {
//收到状态报告了
statusReportService.sendReport(report);
}
}
原始接口获取参数
@WebServlet(urlPatterns = "/smsinterface", name = "SmsServlet")
public class SmsServlet extends HttpServlet {
@Autowired
private SmsCheckService smsCheckService;
@Autowired
private ObjectMapper objectMapper;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
String clientID = req.getParameter("clientID");
String srcID = req.getParameter("srcID");
String mobile = req.getParameter("mobile");
String content = req.getParameter("content");
String pwd = req.getParameter("pwd");//此处应该是一个原始密码
String ip = getRealIp(req);//获取 ip
//校验上面传递过来的数据
//获取真实的数据
BaseResult baseResult = new BaseResult();
try {
//因为内部校验的时候失败是通过抛出异常来进行的,所以我们要捕获异常
smsCheckService.checkSms(clientID, pwd, srcID, ip, content, mobile);
//创建返回结果的对象
baseResult.setCode(InterfaceExceptionDict.RETURN_STATUS_SUCCESS);
baseResult.setMsg("success");
resp.getWriter().write(objectMapper.writeValueAsString(baseResult));
} catch (Exception e) {
e.printStackTrace();
//给返回结果的对象赋值
baseResult.setCode(((SmsInterfaceException) e).getCode());
baseResult.setMsg(((SmsInterfaceException) e).getMsg());
resp.getWriter().write(objectMapper.writeValueAsString(baseResult));
}
}
public static String getRealIp(HttpServletRequest req) {
String ip = null;
//获取请求头中标记的真正的ip
String xIp = req.getHeader("X-Real-IP");
//我们可能会有多次的反向代理
String xFor = req.getHeader("X-Forwarded-For");
//这个 ip 不为空且不是 unknown
if (!StringUtils.isEmpty(xFor) && !"unknow".equalsIgnoreCase(xFor)) {
int index = xFor.indexOf(",");//获取第一个,的位置
if (index > 0) {
return xFor.substring(0, index);
}
return xFor;
}
ip = xIp;//有可能这个 ip 也没有
//当前 ip 是空的
if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
ip = req.getHeader("Proxy-Client-IP");
}
//上面获取的有可能还是空的
if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
ip = req.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
ip = req.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
ip = req.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
}
return ip;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
封装个APi
public class HttpUtil {
public static String doGet(String requestUrl, String token) throws Exception{
HttpURLConnection connection;
//指定访问的地址
URL url = new URL(requestUrl);
connection= (HttpURLConnection) url.openConnection();//打开连接
connection.setDoOutput(true);//允许当前连接向外(服务器)发送数据
connection.setDoInput(true);//允许接受服务器返回的数据
connection.setRequestMethod("GET");
connection.setRequestProperty("jiaobeijiu",token);
connection.connect();//开始连接
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String ss = null;
StringBuffer stringBuffer = new StringBuffer();
while ((ss = bufferedReader.readLine()) != null) {
System.err.println(ss);
stringBuffer.append(ss);
}
connection.disconnect();
return stringBuffer.toString();
}
}
public static String md5Signature(long id, String tradeNo,
String key) {
StringBuffer sb = new StringBuffer();
sb.append(key);
sb.append(id);
sb.append(tradeNo);
sb.append(key);
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String result = null;
try {
result = byte2hex(md.digest(sb.toString().getBytes("utf-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 二行制转字符串
*/
private static String byte2hex(byte[] b) {
StringBuffer hs = new StringBuffer();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs.append("0").append(stmp);
else
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/***
* 对请求的参数排序,生成定长的签名
* @param paramsMap 排序后的字符串
* @param secret 密钥
* */
public static String md5Signature(Map<String, String> paramsMap, String secret) {
Map<String, String> resultMap = new HashMap<String, String>();//用于记录返回的签名和将参数按照签名拼装的url
String result = "";
StringBuilder sb = new StringBuilder();
Map<String, String> treeMap = new TreeMap<String, String>();
treeMap.putAll(paramsMap);
sb.append(secret);
Iterator<String> iterator = treeMap.keySet().iterator();
while (iterator.hasNext()) {
String name = (String) iterator.next();
sb.append(name).append(treeMap.get(name));
}
sb.append(secret);
resultMap.put(PARAMETER_KEY, sb.toString());
try {
MessageDigest md = MessageDigest.getInstance("MD5"); /**MD5加密,输出一个定长信息摘要*/
result = byte2hex(md.digest(sb.toString().getBytes("utf-8")));
} catch (Exception e) {
throw new RuntimeException("sign error !");
}
resultMap.put(SIGN_KEY, result);
return result;
}
/**
* Calculates the MD5 digest and returns the value as a 16 element
* <code>byte[]</code>.
*
* @param data Data to digest
* @return MD5 digest
*/
public static byte[] md5(String data) {
return md5(data.getBytes());
}
/**
* Calculates the MD5 digest and returns the value as a 16 element
* <code>byte[]</code>.
*
* @param data Data to digest
* @return MD5 digest
*/
public static byte[] md5(byte[] data) {
return getDigest().digest(data);
}
/**
* Returns a MessageDigest for the given <code>algorithm</code>.
*
* @param
* @return An MD5 digest instance.
* @throws RuntimeException when a {@link NoSuchAlgorithmException} is
* caught
*/
static MessageDigest getDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
public interface OpenApiRequuest {
/**
* 封装所有请求参数键值对的map
* @return
*/
Map<String, String> getParams();
/**
* 返回令牌
* @return
*/
String getToken();
/**
* 返回用户签名密码的
* @return
*/
String getSecret();
}
public class OrderGetRequest implements OpenApiRequuest {
@Override
public Map<String, String> getParams() {
//"{\"order_id\":\"1\",\"order_state\":\"1\"}"
Map<String, String> map = new HashMap();
map.put("name", "发的撒个房间卡拉斯的环境规划局快乐飞规划局卡拉和技术");
map.put("app_key", "douyin");
map.put("method", "ccc");
map.put("param_json","{\"order_id\":\"1\",\"order_state\":\"1\"}");
return map;
}
@Override
public String getToken() {
return "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInN1aWJpYW54aWUiOlsiUk9MRV9BRE1JTiIsIlJPTEVfVVNFUiJdLCJpYXQiOjE1NzgxMjA1MDksImV4cCI6MTU3ODEyNDEwOX0.AHWwy-6vUOhdCH0GMfNP9WaecWEBvsZMTGbp5L4Ta8E";
}
@Override
public String getSecret() {
return "qishimeiyoumima";
}
}
public class TestServiceRequest implements OpenApiRequuest {
@Override
public Map<String, String> getParams() {
Map<String, String> map = new HashMap();
map.put("name", "发的撒个房间卡拉斯的环境规划局快乐飞规划局卡拉和技术");
map.put("app_key", "douyin");
map.put("method", "bbb");
return map;
}
@Override
public String getToken() {
return "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInN1aWJpYW54aWUiOlsiUk9MRV9BRE1JTiIsIlJPTEVfVVNFUiJdLCJpYXQiOjE1NzgxMjA1MDksImV4cCI6MTU3ODEyNDEwOX0.AHWwy-6vUOhdCH0GMfNP9WaecWEBvsZMTGbp5L4Ta8E";
}
@Override
public String getSecret() {
return "qishimeiyoumima";
}
}
public interface OpenApiClent {
String execute(OpenApiRequuest requuest) throws Exception;
}
public class DefaulrClent implements OpenApiClent {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String execute(OpenApiRequuest requuest) throws Exception {
//通过request中获取各种参数
Map<String, String> params = requuest.getParams();//获取用户传递的参数
params.put("timestamp", simpleDateFormat.format(new Date()));//帮用户补充时间戳参数
String secret = requuest.getSecret();
String sign = Md5Util.md5Signature(params, secret);//帮用户生成签名
params.put("sign", sign);
//name=zhangsan&app_key=dsadasda
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("http://10.9.29.48:14000/?");
for (Map.Entry<String, String> entry : params.entrySet()) {
// stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"UTF-8")).append("&");
}
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
String paramsString = stringBuffer.toString();
// paramsString= paramsString.replaceAll(" ","%20");
// paramsString= URLEncoder.encode(paramsString, "UTF-8");
// System.err.println(paramsString);
String token = requuest.getToken();
return HttpUtil.doGet(paramsString,token);
}
}