• java读取文件推送报文


    接口

     1 package com.lwl.service;
     2 
     3 /**
     4  * 
     5  *
     6  * @author liuwenlong
     7  * @create 2021-11-11 23:48:02
     8  */
     9 @SuppressWarnings("all")
    10 public interface IDevelopService {
    11 
    12     //批量报文推送
    13     String BatchPacketPush(String url, String path, String count, String frequency);
    14 }

    实现类

     1 package com.lwl.service.Impl;
     2 
     3 import com.lwl.service.IDevelopService;
     4 import com.lwl.util.ReadText;
     5 import com.lwl.util.SendPost;
     6 import com.test.controller.BatchPacketPush_test;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Service;
     9 
    10 import java.io.File;
    11 
    12 /**
    13  * @author liuwenlong
    14  * @create 2021-11-11 23:49:21
    15  */
    16 @SuppressWarnings("all")
    17 @Service
    18 public class DevelopServiceImpl implements IDevelopService {
    19 
    20 
    21     /**
    22      * 批量推送报文
    23      *
    24      * @param url       推送地址
    25      * @param path      文件所在路径
    26      * @param count     文件数量
    27      * @param frequency 频率(秒)
    28      * @return
    29      */
    30     @Override
    31     public String BatchPacketPush(String url, String path, String count, String frequency) {
    32         frequency = String.valueOf(Integer.parseInt(frequency) * 1000); //传入的是秒,先转为毫秒
    33         ReadText readText = new ReadText();
    34         SendPost sendPost = new SendPost();
    35         try {
    36             //获取绝对路径下的文件
    37             for (int i = 1; i <= Integer.parseInt(count); i++) {
    38                 String message = readText.readTxt(new File(path + i + ".txt"));
    39                 message = message.replaceAll("\\s*", "");//删除报文中所有空格、空白符等无效字符
    40                 System.out.println(message);
    41                 //拼接报文
    42                 String requestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:les=\"http://www.foton.com.cn/LES_LWL_001_AvailableInventoryInformation\">\n" +
    43                         "   <soapenv:Header/>\n" +
    44                         "   <soapenv:Body>\n" +
    45                         "      <les:LES_LWL_001_AvailableInventoryInformationService>\n" +
    46                         "         <les:DATA><![CDATA[" + message + "]]></les:DATA>\n" +
    47                         "      </les:LES_LWL_001_AvailableInventoryInformationService>\n" +
    48                         "   </soapenv:Body>\n" +
    49                         "</soapenv:Envelope>";
    50                 //请求接口
    51                 String result = sendPost.doPost(url, requestBody);
    52                 System.out.println("响应报文:\n" + result);
    53                 //发送一个报文后,停一段时间,5000毫秒就是5秒
    54                 Thread.sleep(Integer.parseInt(frequency));
    55                 System.out.println("成功发送" + i + "次");
    56             }
    57         } catch (Exception e) {
    58             System.out.println(e.getMessage());
    59         }
    60         return "success";
    61     }
    62 }

    控制层

     1 package com.lwl.controller;
     2 
     3 import com.lwl.entity.Interface;
     4 import com.lwl.service.IDevelopService;
     5 import com.lwl.util.ReadText;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.stereotype.Controller;
     8 import org.springframework.web.bind.annotation.RequestMapping;
     9 
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 import java.io.IOException;
    13 import java.io.PrintWriter;
    14 
    15 /**
    16  * @author liuwenlong
    17  * @create 2021-11-11 23:46:10
    18  */
    19 @SuppressWarnings("all")
    20 @Controller
    21 @RequestMapping(value = "develop")
    22 public class DevelopController {
    23 
    24     @Autowired
    25     IDevelopService iDevelopService;
    26 
    27     /**
    28      * 批量推送报文
    29      *
    30      * @param req
    31      * @param resp
    32      * @param url       推送地址
    33      * @param path      文件所在路径
    34      * @param count     数量
    35      * @param frequency 频率(秒)
    36      * @throws IOException
    37      */
    38     @RequestMapping(value = "BatchPacketPush")
    39     public void BatchPacketPush(HttpServletRequest req, HttpServletResponse resp,
    40                                 String url, String path, String count, String frequency) throws IOException {
    41         resp.setContentType("text/plain; charset=UTF-8");
    42         resp.setCharacterEncoding("UTF-8");
    43         PrintWriter out = resp.getWriter();
    44         String result = iDevelopService.BatchPacketPush(url, path, count, frequency);
    45         System.out.println(result);
    46         out.write(result);
    47         out.flush();
    48     }
    49 }

    工具类-读取文件

     1 package com.lwl.util;
     2 
     3 import java.io.*;
     4 
     5 /**
     6  * 读取文本文件内容
     7  *
     8  * @author liuwenlong
     9  * @create 2021-11-30 22:05:04
    10  */
    11 @SuppressWarnings("all")
    12 public class ReadText {
    13 
    14     /**
    15      * 读文件
    16      *
    17      * @param file 文件
    18      * @return
    19      * @throws IOException
    20      * @throws IOException
    21      */
    22     public static String readTxt(File file) throws IOException, IOException {
    23         String s = "";
    24         InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
    25         BufferedReader br = new BufferedReader(in);
    26         StringBuffer content = new StringBuffer();
    27         while ((s = br.readLine()) != null) {
    28             content = content.append(s);
    29         }
    30         return content.toString();
    31     }
    32 }

    工具类--post请求API接口

     1 package com.lwl.util;
     2 
     3 import sun.misc.BASE64Encoder;
     4 
     5 import java.io.BufferedReader;
     6 import java.io.IOException;
     7 import java.io.InputStreamReader;
     8 import java.io.OutputStreamWriter;
     9 import java.net.HttpURLConnection;
    10 import java.net.URL;
    11 import java.nio.charset.StandardCharsets;
    12 
    13 /**
    14  * post请求
    15  *
    16  * @author liuwenlong
    17  * @create 2021-11-30 22:25:00
    18  */
    19 @SuppressWarnings("all")
    20 public class SendPost {
    21 
    22     /**
    23      * Post请求一个地址
    24      *
    25      * @param URL         请求地址
    26      * @param requestBody 请求的body
    27      * @return
    28      */
    29     public String doPost(String URL, String requestBody) {
    30         OutputStreamWriter out = null;
    31         BufferedReader in = null;
    32         StringBuilder result = new StringBuilder();
    33         HttpURLConnection conn = null;
    34         String username = "账号";
    35         String password = "密码";
    36         String input = username + ":" + password;
    37         try {
    38             java.net.URL url = new URL(URL);
    39             conn = (HttpURLConnection) url.openConnection();
    40             BASE64Encoder base = new BASE64Encoder();
    41             String encodedPassword = base.encode(input.getBytes("UTF-8"));
    42             System.out.println("加密后的密码:" + encodedPassword);
    43             //将加密的账号密码放到请求头里,这里注意Basic后面要加空格
    44             conn.setRequestProperty("Authorization", "Basic " + encodedPassword);
    45             conn.setRequestMethod("POST");
    46             //发送POST请求必须设置为true
    47             conn.setDoOutput(true);
    48             conn.setDoInput(true);
    49             //设置连接超时时间和读取超时时间
    50             conn.setConnectTimeout(3000);
    51             conn.setReadTimeout(3000);
    52             conn.setRequestProperty("Content-Type", "application/json");
    53             conn.setRequestProperty("Accept", "application/json");
    54             //获取输出流,写入请求的json报文
    55             out = new OutputStreamWriter(conn.getOutputStream());
    56             System.out.println(requestBody);
    57 
    58             out.write(requestBody); //获取请求的body,
    59             out.flush();
    60             out.close();
    61             //取得输入流,并使用Reader读取
    62             if (200 == conn.getResponseCode()) {
    63                 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
    64                 String line;
    65                 while ((line = in.readLine()) != null) {
    66                     result.append(line);
    67                     System.out.println(line);
    68                 }
    69             } else {
    70                 System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
    71             }
    72         } catch (Exception e) {
    73             e.printStackTrace();
    74         } finally {
    75             try {
    76                 if (out != null) {
    77                     out.close();
    78                 }
    79                 if (in != null) {
    80                     in.close();
    81                 }
    82             } catch (IOException ioe) {
    83                 ioe.printStackTrace();
    84             }
    85         }
    86         return result.toString();
    87     }
    88 }

    前端页面

     1 <html>
     2 <head>
     3     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     4     <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
     5     <link rel="icon" th:href="@{/public/favicon.ico}" type="image/x-icon"/>
     6     <link rel="bookmark" th:href="@{/public/favicon.ico}" type="image/x-icon"/>
     7     <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
     8     <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
     9     <script type="text/javascript" src="${pageContext.request.contextPath}/static/wms/Js/jquery-1.7.2.min.js"></script>
    10 </head>
    11 
    12 
    13 <script>
    14 
    15     function BtnBatchPacketPush(text, reviver) {
    16 
    17         const url = $('#url').val().toString();
    18         const path = $('#path').val().toString();
    19         const count = $('#count').val().toString();
    20         const frequency = $('#frequency').val().toString();
    21 
    22         $.ajax({
    23             method: 'post',
    24             url: "${pageContext.request.contextPath}/develop/BatchPacketPush",
    25             data: {
    26                 "url": url,
    27                 "path": path,
    28                 "count": count,
    29                 "frequency": frequency
    30             },
    31             success: function (res) {
    32                 if (res !== "") {
    33                     alert(res.toString())
    34                 } else {
    35                     alert("发送失败!")
    36                 }
    37             }
    38         })
    39     }
    40 </script>
    41 
    42 <body>
    43 
    44 
    45 
    46 <div style=" 100%;height: 850px;background: white;margin-top: 10px;padding: 10px">
    47 
    48 
    49         <div class="layui-form-item">
    50             <label class="layui-form-label">请求地址</label>
    51             <div class="layui-input-block">
    52                 <input type="text" id="url" name="url" required lay-verify="required" placeholder="请输入接口地址"
    53                        autocomplete="off" class="layui-input">
    54             </div>
    55         </div>
    56 
    57         <div class="layui-form-item">
    58             <label class="layui-form-label">文件路径</label>
    59             <div class="layui-input-block">
    60                 <input type="text" id="path" name="path" required lay-verify="required" placeholder="请输入报文所在的路径"
    61                        autocomplete="off" class="layui-input">
    62             </div>
    63             <div class="layui-form-mid layui-word-aux">D:\\报文推送\\</div>
    64         </div>
    65 
    66         <div class="layui-form-item">
    67             <label class="layui-form-label">文件数量</label>
    68             <div class="layui-input-inline">
    69                 <input type="text" id="count" name="count" lay-verify="required" placeholder="请输入文件数量"
    70                        autocomplete="off" class="layui-input">
    71             </div>
    72         </div>
    73 
    74         <div class="layui-form-item">
    75             <label class="layui-form-label">推送间隔</label>
    76             <div class="layui-input-inline">
    77                 <input type="text" id="frequency" name="frequency" lay-verify="required" placeholder="报文请求频率"
    78                        autocomplete="off" class="layui-input">
    79             </div>
    80             <div class="layui-form-mid layui-word-aux">(秒)</div>
    81         </div>
    82 
    83 
    84         <div class="layui-form-item">
    85             <div class="layui-input-block">
    86                 <button class="layui-btn" lay-submit lay-filter="formDemo" type="button" onclick="BtnBatchPacketPush();">
    87                     立即提交
    88                 </button>
    89                 <button type="button" class="layui-btn layui-btn-primary">重置</button>
    90 
    91             </div>
    92         </div>
    93 
    94 </div>
    95 
    96 </div>
    97 
    98 </body>
    99 </html>

    数据文件

     执行

     后端执行

    原创文章,转载请说明出处,谢谢合作
  • 相关阅读:
    几种 JavaScript 动画库推荐
    微软工程师为你推荐了十本程序员必读书目
    前端新老手必备的34种JavaScript简写优化技术
    Airbnb 爱彼迎 visx 项目介绍
    开源中间件技术支持(5000+元/天)
    C# Byte数组与Int16数组之间的转换(转)
    【636】K.sum 与 np.sum 的区别
    【635】语义分割 label 通道与模型输出通道的
    【634】ndarray 提取行列进行任意变换 & 相关 ndarray 操作
    面试官:设计一个安全的登录都要考虑哪些?我一脸懵逼。。
  • 原文地址:https://www.cnblogs.com/lwl80/p/15627080.html
Copyright © 2020-2023  润新知