请求其他端口的服务
1、请求端01
js
// 将窗口RA数据推送至校验数据库 function checkCert(zsxh,ywlx,zstype) { $.ajax({ type: "post", url: "${ck}/SSOPush/manager", data: {"zsxh": zsxh,"ywlx":ywlx,radom:Math.random(),"zstype":zstype}, dataType: "json", error: function() {} }); }
控制器
package com.xjca.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.xjca.service.CheckCertService; @Controller @RequestMapping("/SSOPush") public class CheckCertController { @Autowired CheckCertService checkCertService; @RequestMapping("/manager") public void manager(String zsxh,String ywlx,String zstype){ //推送tb_user和tb_user checkCertService.pushDate(zsxh,ywlx,zstype); } }
CheckCertService实现类:
package com.xjca.service.impl; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.ecs.xhtml.object; import org.apache.ecs.xhtml.th; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xjca.dao.CheckCertDao; import com.xjca.pagemodel.CkDataPushPageModel; import com.xjca.service.CheckCertService; import com.xjca.service.CkDataPushSerive; import com.xjca.util.HttpClientUtils; /** * 推送数据的实现 * * @author mabin * @date 2021-08-10 */ @Service public class CheckCertServiceImpl implements CheckCertService{ @Autowired CheckCertDao checkCertDao; @Autowired CkDataPushSerive dataPushSerive; private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(OcciServiceImpl.class); @Override public void pushDate(String zsxh,String ywlx,String zstype) { try { //查出ra对应的userid和证书的cn String sql = "select t.yhmc,t.userid from ckywsqbzs t where t.zsxh=?"; List<Map<String, Object>> listYhmc = checkCertDao.sqlQueryMap(sql, new Object[]{zsxh}); String cn = listYhmc.get(0).get("YHMC").toString(); String userId = listYhmc.get(0).get("USERID").toString(); List<Map<String, Object>> listUsertId=null; if(StringUtils.isNotBlank(cn)){ //补办证书业务 if ("5".equals(ywlx)) { //修改检查库状态 this.pushUpdateRAUserCertStatus(userId,"-1",zstype); //推送usercert数据 this.pushRAUserCert(userId,"1",zstype); } //新办证书业务 if ("1".equals(ywlx)) { //ra库里面查询的该证书的数据,并推送ra数据 listUsertId = this.pushRAUser(cn,zstype); if (listUsertId.size()> 0) { //推送usercert数据 this.pushRAUserCert(userId,"1",zstype); } } } } catch (Exception e) { e.printStackTrace(); } } /** * * @param cn 证书的cn值 * @param zstype rsa和sm2 * @return * 推送ra的user数据 */ private List<Map<String, Object>> pushRAUser(String cn, String zstype){ List<Map<String, Object>> list=null; try { String sql=null; if("sm2".equals(zstype)){ sql = "select t.user_id,t.CERT_CN,to_char(t.USER_CREATE_DATE,'yyyy-MM-dd HH:mm:ss')USER_CREATE_DATE,t.USER_STATUS_ID,t.RA_ID,t.LAST_OPERATOR_ID,t.USER_CERT_TYPE,t.USER_IDNO,t.USER_COUNTRY,t.USER_CITY,t.USER_ORG,t.USER_ORG_UNIT " + "from tb_user@xjca_ra_sm2 t where t.cert_cn=?"; } if ("rsa".equals(zstype)) { sql = "select t.user_id,t.CERT_CN,to_char(t.USER_CREATE_DATE,'yyyy-MM-dd HH:mm:ss')USER_CREATE_DATE,t.USER_STATUS_ID,t.RA_ID,t.LAST_OPERATOR_ID,t.USER_CERT_TYPE,t.USER_IDNO,t.USER_COUNTRY,t.USER_CITY,t.USER_ORG,t.USER_ORG_UNIT " + "from tb_user t where t.cert_cn=?"; } list = checkCertDao.sqlQueryMap(sql, new Object[]{cn}); if (list.size() > 0) { Map<String, Object> map = list.get(0); String url = "http://192.168.117.140:8083/insertUser"; JSONObject jsonParam = new JSONObject(); jsonParam.put("userId",map.get("USER_ID")); jsonParam.put("certCn", map.get("CERT_CN")); jsonParam.put("userStatusId", map.get("USER_STATUS_ID")); jsonParam.put("raId", map.get("RA_ID")); jsonParam.put("lastOperatorId", map.get("LAST_OPERATOR_ID")); jsonParam.put("userCertType", map.get("USER_CERT_TYPE")); jsonParam.put("userIdno", map.get("USER_IDNO")); jsonParam.put("userCountry", map.get("USER_COUNTRY")); jsonParam.put("userCity", map.get("USER_CITY")); jsonParam.put("userOrg", map.get("USER_ORG")); jsonParam.put("userOrgUnit", map.get("USER_ORG_UNIT")); jsonParam.put("userCreateDate", map.get("USER_CREATE_DATE")); this.post(url, jsonParam); } } catch (Exception e) { e.printStackTrace(); } return list; } /** * * @param userid * @param status 状态 * @param zstype 证书的类型 * 推送tb_user_cert表 */ private void pushRAUserCert(String userid,String status,String zstype) { try { String sql=null; if("sm2".equals(zstype)){ sql = "select t.cert_id,t.user_id,t.CERT_STATUS_ID,t.CERT_SN,to_char(t.CERT_NOT_BEFORE,'yyyy-MM-dd HH:mm:ss') CERT_NOT_BEFORE,to_char(t.CERT_NOT_AFTER,'yyyy-MM-dd HH:mm:ss') CERT_NOT_AFTER,t.CERT_POLICY_NAME"+ " from tb_user_cert@xjca_ra_sm2 t where t.user_id=? and t.cert_status_id='1'"; } if("rsa".equals(zstype)){ sql = "select t.cert_id,t.user_id,t.CERT_STATUS_ID,t.CERT_SN,to_char(t.CERT_NOT_BEFORE,'yyyy-MM-dd HH:mm:ss') CERT_NOT_BEFORE,to_char(t.CERT_NOT_AFTER,'yyyy-MM-dd HH:mm:ss') CERT_NOT_AFTER,t.CERT_POLICY_NAME"+ " from tb_user_cert t where t.user_id=? and t.cert_status_id='1'"; } List<Map<String, Object>> list = checkCertDao.sqlQueryMap(sql, new Object[]{userid}); if (list.size() > 0) { Map<String, Object> map = list.get(0); String url = "http://192.168.117.140:8083/insertUserCert"; JSONObject jsonParam = new JSONObject(); jsonParam.put("certId",map.get("CERT_ID")); jsonParam.put("userId", map.get("USER_ID")); jsonParam.put("certStatusId", map.get("CERT_STATUS_ID")); jsonParam.put("certSn", map.get("CERT_SN")); jsonParam.put("certType",zstype); jsonParam.put("certNotBefore", map.get("CERT_NOT_BEFORE")); jsonParam.put("certNotAfter", map.get("CERT_NOT_AFTER")); jsonParam.put("certPolicyName", map.get("CERT_POLICY_NAME")); this.post(url, jsonParam); } } catch (Exception e) { e.printStackTrace(); } } /** * * @param userid * @param status * @param certType * 推送修改证书状态记录 */ private void pushUpdateRAUserCertStatus(String userid,String status, String certType) { try { String sql = null; if("sm2".equals(certType)){ sql = "select t.cert_id,t.user_id,t.CERT_STATUS_ID,t.CERT_SN,to_char(t.CERT_NOT_BEFORE,'yyyy-MM-dd HH:mm:ss') CERT_NOT_BEFORE,to_char(t.CERT_NOT_AFTER,'yyyy-MM-dd HH:mm:ss') CERT_NOT_AFTER,t.CERT_POLICY_NAME"+ " from tb_user_cert@xjca_ra_sm2 t where t.user_id=? and t.CERT_STATUS_ID=? and cert_sn=(select max(t.cert_sn) from tb_user_cert@xjca_ra_sm2 t where user_id=? and t.cert_status_id='-1') "; } if ("rsa".equals(certType)) { sql = "select t.cert_id,t.user_id,t.CERT_STATUS_ID,t.CERT_SN,to_char(t.CERT_NOT_BEFORE,'yyyy-MM-dd HH:mm:ss') CERT_NOT_BEFORE,to_char(t.CERT_NOT_AFTER,'yyyy-MM-dd HH:mm:ss') CERT_NOT_AFTER,t.CERT_POLICY_NAME"+ " from tb_user_cert t where t.user_id=? and t.CERT_STATUS_ID=? and cert_sn=(select max(t.cert_sn) from tb_user_cert t where user_id=? and t.cert_status_id='-1') "; } List<Map<String, Object>> list = checkCertDao.sqlQueryMap(sql, new Object[]{userid,status,userid}); if (list.size() > 0) { Map<String, Object> map = list.get(0); String url = "http://192.168.117.140:8083/updateCertStatus"; JSONObject jsonParam = new JSONObject(); jsonParam.put("certId",map.get("CERT_ID")); jsonParam.put("userId", map.get("USER_ID")); jsonParam.put("certStatusId", map.get("CERT_STATUS_ID")); jsonParam.put("certSn", map.get("CERT_SN")); jsonParam.put("certType", certType); jsonParam.put("certNotBefore", map.get("CERT_NOT_BEFORE")); jsonParam.put("certNotAfter", map.get("CERT_NOT_AFTER")); jsonParam.put("certPolicyName", map.get("CERT_POLICY_NAME")); this.post(url, jsonParam); } } catch (Exception e) { e.printStackTrace(); } } /** * * @param url * @param jsonParam * 向检查服务发送请求 */ private void post(String url, JSONObject jsonParam) { CkDataPushPageModel model = new CkDataPushPageModel(); model.setUrl(url); model.setParam(jsonParam.toString()); String result = ""; try { result = HttpClientUtils.httpPost(url, jsonParam); System.out.println(result); if("".equals(result)){ //返回的请求是空的,将数据保存到库里面,用定时任务推送 this.dataPushSerive.add(model); }else { JSONObject paramResult = JSONObject.fromObject(result); if (paramResult.getInt("code") != 200) { //推送失败将数据保存到库里面,用定时任务推送 this.dataPushSerive.add(model); } } } catch (Exception e) { log.error(" >>> : CheckCertServiceImpl类,方法 post,产生异常Exception,数据推送接口调用失败," + e.getMessage(), e); //出现异常,将数据保存到库里面,用定时任务推送 this.dataPushSerive.add(model); } } }
HttpClientUtils.httpPost代码:
package com.xjca.util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; import org.apache.log4j.Logger; /** * HttpClient工具类 * * @author cl * @date 2021-06-10 */ public class HttpClientUtils { // 日志记录 private static Logger logger = Logger.getLogger(HttpClientUtils.class); /** * post请求传输json参数 * * @author cl * @throws Exception * @date 2021-06-10 */ public static String httpPost(String URL, JSONObject jsonParam) throws Exception { logger.info("-------------------------------接口请求入口-------------------------------"); logger.info("接口请求 url:" + URL); logger.info("接口请求参数:" + jsonParam.toString()); String jsonString = ""; // 创建连接 URL url = new URL(URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); // 设置请求方法 connection.setRequestProperty("Charsert", "UTF-8"); // 设置请求编码 connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); out.println(jsonParam.toString()); out.flush(); out.close(); // 读取响应 返回值为200输出的响应信息 if (connection.getResponseCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } jsonString = sb.toString().replaceAll(" ", ""); reader.close(); } // 读取响应 返回值为400输出的响应信息 if (connection.getResponseCode() == 400) { BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getErrorStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } jsonString = sb.toString(); reader.close(); } // 断开连接 connection.disconnect(); logger.info("接口相应结果:" + jsonString); logger.info("-------------------------------接口请求出口-------------------------------\r\n"); return jsonString; }
//测试 public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("proNo", "HY2021060941143"); obj.put("proName", "新疆电力交易平台"); obj.put("feeNo", "SF2021061699814"); obj.put("feeName", "手动阀手动阀"); obj.put("feePrice", 600); obj.put("yearLimit", "1"); obj.put("type", "1"); String url = "http://127.0.0.1:82/czs/etp/add"; try { HttpClientUtils.httpPost(url, obj); } catch (Exception e) { e.printStackTrace(); } } }
2、请求端02(hutool工具类方式实现)
package com.xjca;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjca.mapping.PushDataMapper;
import com.xjca.pojo.CkDataPush;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service
public class ScheduledService {
@Autowired
PushDataMapper pushDataMapper;
//定时推送数据,每两秒执行一次
@Scheduled(cron = "0/2 * * * * ?")
public void pushData(){
System.out.println("进入定时任务");
//查询条件
QueryWrapper<CkDataPush> queryWrapper = new QueryWrapper<>();
queryWrapper.likeRight("url","http://192.168.117.140:8083");
//获取查询到的数据
List<CkDataPush> list = pushDataMapper.selectList(queryWrapper);
//如果有数据就重新推送
if(list.size() > 0){
for (CkDataPush ckDataPush:list){
System.out.println(ckDataPush);
//请求接口
String result = HttpUtil.createPost(ckDataPush.getUrl()).body(ckDataPush.getParam()).execute().body();
if (StringUtils.isNotBlank(result)){
System.out.println(result);
//推送完以后就将该数据删除
HashMap<String, Object> deletemap = new HashMap<>();
deletemap.put("id",ckDataPush.getId());
int deleteResult = pushDataMapper.deleteByMap(deletemap);
}
}
}
}
}
接收端。主要是控制器,要保证接收端的控制器可以跑通,测试特重要:
控制器:
package com.xjca.controller; import com.xjca.pagemodel.XjcaJson; import com.xjca.pojo.TbUser; import com.xjca.pojo.TbUserCert; import com.xjca.service.CheckService; import com.xjca.service.TbUserCertService; import com.xjca.service.TbUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; @RestController @SuppressWarnings("All") public class CheckController { @Autowired private TbUserService tbUserService; @Autowired private CheckService checkService; @Autowired private TbUserCertService tbUserCertService; /** * * @param tbUser tb_user表映射的对象 * @return * */ @PostMapping("insertUser") public XjcaJson insertUser(@RequestBody TbUser tbUser) { XjcaJson xjcaJson = new XjcaJson(); try { System.out.println(tbUser); Integer result = tbUserService.insert(tbUser); if (result > 0) { xjcaJson.setSucc(true); xjcaJson.setCode("200"); xjcaJson.setMsg("User数据插入成功"); } } catch (Exception e) { xjcaJson.setSucc(false); xjcaJson.setCode("500"); xjcaJson.setMsg("User数据插入失败"); e.printStackTrace(); } return xjcaJson; } @PostMapping("insertUserCert") public XjcaJson insertUserCert(@RequestBody TbUserCert tbUserCert) { XjcaJson xjcaJson = new XjcaJson(); try { System.out.println(tbUserCert); Integer result = tbUserCertService.insert(tbUserCert); if (result > 0) { xjcaJson.setSucc(true); xjcaJson.setCode("200"); xjcaJson.setMsg("UserCert数据插入成功"); } } catch (Exception e) { xjcaJson.setSucc(false); xjcaJson.setCode("500"); xjcaJson.setMsg("UserCert数据插入失败"); e.printStackTrace(); } return xjcaJson; } @RequestMapping("checkCert/{sn}") @ResponseBody public XjcaJson checkCert(@PathVariable(value = "sn", required = false) String sn) { XjcaJson xjcaJson = checkService.checkCert(sn); return xjcaJson; } //将证书的状态改成-1 @RequestMapping("updateCertStatus") @ResponseBody public XjcaJson updateCertStatusFC(@RequestBody TbUserCert tbUserCert) { XjcaJson xjcaJson = new XjcaJson(); try { Integer result = tbUserCertService.updateCertStatusFC(tbUserCert); if (result>0){ xjcaJson.setSucc(true); xjcaJson.setCode("200"); xjcaJson.setMsg("UserCert数据更新成功"); } }catch (Exception e){ xjcaJson.setSucc(false); xjcaJson.setCode("500"); xjcaJson.setMsg("UserCert数据更新失败"); } return xjcaJson; } }
本文来自博客园,作者:极地阳光-ing,转载请注明原文链接:https://www.cnblogs.com/Polar-sunshine/p/15147209.html