Java应急广播平台接口对接demo(以 应急广播消息格式规范为例)

 对接应急广播渠道,自己做的一个测试demo,记录一下,仅供自己日后回顾学习。

此版本为ssh+tomcat7+jdk7,另有springboot版本+jdk8,已上传资源文件gitee。

public JSONObject sendBroadCast(BoardCastConfig config){
		//获取发布内容
		String issueText = pubMessage.getPubreason();
		//广播接口 -集成测试淮北互联网接口地址
		String boardcastUrl = config.getUrl();
		//组装xml文件:
		File dataxml = createXml(pubMessage);
		//将文件压缩为tar文件
		String targetTar=dataxml.getAbsolutePath().substring(0, dataxml.getAbsolutePath().lastIndexOf(".")).replace("EBDB", "EBDT")+".tar";
		System.out.println("targetTar-==="+targetTar);
		File senddataTar = toCompress(dataxml, dataxml.getAbsolutePath().substring(0, dataxml.getAbsolutePath().lastIndexOf(".")).replace("EBDB", "EBDT")+".tar");
		System.out.println(senddataTar.getName());
		try{
			System.out.println("=================应急广播开始发送文件============");
			//发送文件:
			//File responseTar = HttpUtils.sendbroadPost(broadcastURL, senddataTar,filepath);
			File responseTar = HttpUtils.sendbroadPost(boardcastUrl, senddataTar,"D:\\test");
			System.out.println("=================应急广播解压返回文件==================");
			//解压返回的数据
//			File file = uncompress(responseTar, filepath);
			File file = uncompress(responseTar, "D:\\test");
			System.out.println("解压后的文件:"+file.getName());
			System.out.println("=================应急广播开始解析文件========================");
			//解析数据
			JSONObject jsonObject = parseFile(file);
			JSONObject parseFile = jsonObject;
			System.out.println("=================应急广播解析文件结束========================");
			System.out.println("=========应急广播返回结果============"+parseFile.get("resultCode"));
			System.out.println("================应急广播解析完毕=============================");
			return jsonObject;
		}catch(Exception e){
			e.printStackTrace(); 
			JSONObject json = new JSONObject();
			json.put("result", 2);
			json.put("msg", e.toString());
			return json;
		}
	}

 

public class HttpUtils {
	public static File sendbroadPost(String srcurl,File file,String filepath){
		try {
			String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线

			URL url = new URL(srcurl);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			// 发送POST请求必须设置如下两行

			conn.setDoOutput(true);

			conn.setDoInput(true);

			conn.setUseCaches(false);

			conn.setRequestMethod("POST");

			conn.setRequestProperty("connection", "Keep-Alive");

			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

			conn.setRequestProperty("Charsert", "UTF-8");

			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());

			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线


			StringBuilder sb = new StringBuilder();

			sb.append("--");

			sb.append(BOUNDARY);

			sb.append("\r\n");

			sb.append("Content-Disposition: form-data;name=\"filed1\";filename=\""+ "EBDT_10223000000000000010101030000000000000414.tar" + "\"\r\n");

			sb.append("Content-Type:application/x-tar\r\n\r\n");

			byte[] data = sb.toString().getBytes();

			out.write(data);

			DataInputStream in = new DataInputStream(new FileInputStream(file));

			int bytes = 0;

			byte[] bufferOut = new byte[1024];

			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);

			}

			out.write(end_data);

			out.flush();

			out.close();

			System.out.println("===================广播文件发送完毕===============");
			if(conn.getResponseCode() == 200){
				System.out.println("====================开始接收文件=========================");
				InputStream inputStream = conn.getInputStream();
				File resFile = new File(filepath,"test1.tar");
				FileOutputStream resOut = new FileOutputStream(resFile);
				int len = 0;
				byte[] b = new byte[1024];
				while((len = inputStream.read(b))!= -1){
					resOut.write(b, 0, len);
				}
				resOut.close();
				inputStream.close();
				return resFile;
			}else{
				System.out.println("响应失败");
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常!" + e);

			e.printStackTrace();

		}
		return null;
	}

}
public File createXml(PubMessage pubMessage) {
		try{
			//1.创建document对象
			Document document = DocumentHelper.createDocument();
			//2.创建根节点
			Element root = document.addElement("EBD");
			root.addAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
			Element EBDVersion = root.addElement("EBDVersion");
			EBDVersion.addText("1.0");
			Element EBDID = root.addElement("EBDID");
			EBDID.addText("10234000000000000010101010000000040694582");//43位id-------------
			Element EBDType = root.addElement("EBDType");
			EBDType.addText("EBM");
			//src标签
			Element SRC = root.addElement("SRC");
			Element EBRID = SRC.addElement("EBRID");
			EBRID.addText("23400000000000001010101");//EBRID--------------
			Element URL = SRC.addElement("URL");
			URL.addText("http://上级平台ip:8080/bjyujing");
			//dest标签
			Element DEST = root.addElement("DEST");
			Element EBRID_dest = DEST.addElement("EBRID");
			EBRID_dest.addText("33406000000000103010101");
			
			//数据包生成时间
			SimpleDateFormat sdfpub = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String EBDTimeStr = sdfpub.format(new Date());
			Element EBDTime = root.addElement("EBDTime");
			EBDTime.addText(EBDTimeStr);

			//组装EBM
			Element EBM = root.addElement("EBM");
			Element EBMVersion = EBM.addElement("EBMVersion");
			EBMVersion.addText("1");
			Element EBMID = EBM.addElement("EBMID");
			EBMID.addText("23400000000000001010101202105266767");//EBMID-----------------------
			
			//组装EBM的MsgBasicInfo
			Element MsgBasicInfo = EBM.addElement("MsgBasicInfo");
			Element MsgType = MsgBasicInfo.addElement("MsgType");
			//消息的类型,		1:实际播发		2:取消播发		3:平台演练播发		4:前端演练播发		5:终端演练播发
			MsgType.addText("1");
			Element SenderName = MsgBasicInfo.addElement("SenderName");
			//SenderName.addText(pubMessage.getOrgName());//应急信息发布机构的全称
			SenderName.addText("安徽省调度控制平台");
			Element SenderCode = MsgBasicInfo.addElement("SenderCode");
			//SenderCode.addText(pubMessage.getOrgcode());//应急信息发布机构的编码
			SenderCode.addText("23400000000000001010101");
			Element SendTime = MsgBasicInfo.addElement("SendTime");
			SendTime.addText(sdfpub.format(new Date()));
			Element EventType = MsgBasicInfo.addElement("EventType");
			//当前type所需为预警类型:当前预警生成没有预警类型,暂写死为空串
			EventType.addText(pubMessage.getType());
			Element Severity = MsgBasicInfo.addElement("Severity");
			String level = "01".equals(pubMessage.getYjlevel()) ? "1" : "02".equals(pubMessage.getYjlevel()) ? "2"
					: "03".equals(pubMessage.getYjlevel()) ? "3" : "04".equals(pubMessage.getYjlevel()) ? "4" : "0";
			Severity.addText(level);//预警级别
			Element StartTime = MsgBasicInfo.addElement("StartTime");
			StartTime.addText(sdfpub.format(new Date()));
			Element EndTime = MsgBasicInfo.addElement("EndTime");
			EndTime.addText(sdfpub.format(new Date()));


			//组装msgContent
			Element MsgContent = EBM.addElement("MsgContent");
			Element LanguageCode = MsgContent.addElement("LanguageCode");
			LanguageCode.addText("zho");
			Element MsgTitle = MsgContent.addElement("MsgTitle");
			//			MsgTitle.addText(pubMessage.getTitle());
			MsgTitle.addText("淮北市应急广播");
			Element MsgDesc = MsgContent.addElement("MsgDesc");
			//			MsgDesc.addText(pubMessageServiceImpl.getIssueText(pubMessage.getId(), cannelId));
			MsgDesc.addText("【测试应急广播】当前为应急广播渠道测试,请忽略,如有打扰请谅解");
			String pubdistrict = "";
			StringBuffer sb = new StringBuffer();
			//发布区域 多个用逗号隔开-
//			List<String> list = Arrays.asList(pubMessage.getPubdistrict().split(","));
//			if (list != null && list.size()>0) {
//				for (int i = 0;i<list.size();i++) {
//					if(i != list.size()-1){
//						pubdistrict+=list.get(i)+",";
//					}else{
//						pubdistrict += list.get(i);
//					}
//				}
//			}
			Element AreaCode = MsgContent.addElement("AreaCode");
			//AreaCode.addText(pubdistrict);
			AreaCode.addText("340602401000");
			
			Element ProgramNum = MsgContent.addElement("ProgramNum");
			ProgramNum.addText("0");
			// 5、设置生成xml的格式
			OutputFormat format = OutputFormat.createPrettyPrint();
			// 设置编码格式
			format.setEncoding("UTF-8");


			// 6、生成xml文件			
			File file = new File("D:/test"+"/EBDB_10223000000000000010101030000000000000414.xml");
			XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
			// 设置是否转义,默认使用转义字符
			writer.setEscapeText(false);
			writer.write(document);
			writer.close();
			System.out.println("生成应急广播请求文件成功");
			return file;
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
//把文件打包成tar包
	public File toCompress(File sourceFile,String tarFilrPath) {  
			FileOutputStream dest;  
			TarOutputStream tarOut;  
			try {  
				//设置tar包位置
				File file = new File(tarFilrPath);
				dest = new FileOutputStream(file);  
				tarOut = new TarOutputStream(new BufferedOutputStream(dest));
				//设置待打包源文件的位置
				tarOut.putNextEntry(new TarEntry(sourceFile, sourceFile.getName()));  
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));  
				int count;  
				byte data[] = new byte[2048];  
				while ((count = bis.read(data)) != -1) {  
					tarOut.write(data, 0, count);  
				}  
				tarOut.flush();  
				bis.close();  

				tarOut.close();  
				return file;
			} catch (FileNotFoundException e) {  
				e.printStackTrace();  
			} catch (IOException e) {  
				e.printStackTrace();  
			}  
			return null;
		}
public File uncompress(File sourceFile,String FilePath) { 
		InputStream inputstream = null; 
		OutputStream outputstream = null; 
		TarInputStream zis = null; 
		File tempFile = null; 
		try { 
			
			//读取压缩包的内容
			inputstream = new FileInputStream(sourceFile); 
			zis = new TarInputStream(inputstream); 
			//tarEntry:每一个文件对应一个tarEntry
			TarEntry tarEntry = null; 
			while ((tarEntry = zis.getNextEntry()) != null) { 
				String path = FilePath+"//"+ tarEntry.getName();
				tempFile = new File(path); 
				if(!tempFile.exists()){
					tempFile.createNewFile();
				}
				outputstream = new FileOutputStream(tempFile); 
				//定义一个缓冲池,缓冲池的大小,决定着每次读取的数据量大小,可以根据实际要处理的数据量大小和服务器的自身的配置,对其进行修改
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len = zis.read(buffer))!=-1){
					outputstream.write(buffer, 0, len);
				}
			}
			return tempFile;
		} catch (Exception e) { 
			e.printStackTrace(); 
			System.out.println("=============解压应该广播返回文件异常==============");
		} finally { 
			try { 
				outputstream.flush(); 
				inputstream.close(); 
				zis.close(); 
				outputstream.close(); 
			} catch (Exception e) { 
				e.printStackTrace(); 
			} 

		} 
		return null;
	}

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hidetou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值