• http文件导出写文件


    jxl

    <dependency>
    			<groupId>net.sourceforge.jexcelapi</groupId>
    			<artifactId>jxl</artifactId>
    			<version>2.6.12</version>
    		</dependency>
    

      ReadExcel

    将xlsx 用excle打开另存为为xls

    读取excle

    public class  ReadExcel{
    
        private String filePath;
    
    
    
        private List<String[]> list = new ArrayList();
    
        public ReadExcel(String filePath){
            this.filePath = filePath;
        }
    
        public List<String[]> readExcel() throws IOException, BiffException{
            //创建输入流  
            InputStream stream = new FileInputStream(filePath);
            //获取Excel文件对象  
            Workbook  rwb = Workbook.getWorkbook(stream);
            //获取文件的指定工作表 默认的第一个  
            Sheet sheet = rwb.getSheet(0);
            //行数(表头的目录不需要,从1开始)  
            for(int i=0; i<sheet.getRows(); i++){
                //创建一个数组 用来存储每一列的值
                String[] str = new String[sheet.getColumns()];
                Cell cell = null;
                //列数  
                for(int j=0; j<sheet.getColumns(); j++){
                    //获取第i行,第j列的值
                    cell = sheet.getCell(j,i);
                    str[j] = cell.getContents();
                }
                //把刚获取的列存入list
                list.add(str);
            }
            return list;
        }
        public void outData(){
            for(int i=0;i<list.size();i++){
                String[] str = (String[])list.get(i);
                for(int j=0;j<str.length;j++){
                    System.out.print(str[j]+'	');
                }
                System.out.println();
            }
        }
    
        public static void main(String args[]) throws BiffException, IOException{
            ReadExcel excel = new ReadExcel("C:\Users\hasee\Documents\263EM\108251@ycgwl.com\receive_file\aa.xls");
            excel.readExcel();
            excel.outData();
        }
    }
    View Code

    FileOperation

    写文件

    public class FileOperation {
    
        /**
         * 创建文件
         * @param fileName
         * @return
         */
        public static boolean createFile(File fileName)throws Exception{
            boolean flag=false;
            try{
                if(!fileName.exists()){
                    fileName.createNewFile();
                    flag=true;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return true;
        }
    
        /**
         * 读TXT文件内容
         * @param fileName
         * @return
         */
        public static String readTxtFile(File fileName)throws Exception{
            String result=null;
            FileReader fileReader=null;
            BufferedReader bufferedReader=null;
            try{
                fileReader=new FileReader(fileName);
                bufferedReader=new BufferedReader(fileReader);
                try{
                    String read=null;
                    while((read=bufferedReader.readLine())!=null){
                        result=result+read+"
    ";
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(bufferedReader!=null){
                    bufferedReader.close();
                }
                if(fileReader!=null){
                    fileReader.close();
                }
            }
            System.out.println("读取出来的文件内容是:"+"
    "+result);
            return result;
        }
    
    
        public static boolean writeTxtFile(String content,File  fileName)throws Exception{
            RandomAccessFile mm=null;
            boolean flag=false;
            FileOutputStream o=null;
            try {
                o = new FileOutputStream(fileName);
                o.write(content.getBytes("GBK"));
                o.close();
    //   mm=new RandomAccessFile(fileName,"rw");
    //   mm.writeBytes(content);
                flag=true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally{
                if(mm!=null){
                    mm.close();
                }
            }
            return flag;
        }
    
    
    
        public static void contentToTxt(String filePath, String content) {
            String str = new String(); //原有txt内容
            String s1 = new String();//内容更新
            try {
                File f = new File(filePath);
                if (f.exists()) {
                    System.out.print("文件存在");
                } else {
                    System.out.print("文件不存在");
                    f.createNewFile();// 不存在则创建
                }
                BufferedReader input = new BufferedReader(new FileReader(f));
    
                while ((str = input.readLine()) != null) {
                    s1 += str + "
    ";
                }
                System.out.println(s1);
                input.close();
                s1 += content;
    
                BufferedWriter output = new BufferedWriter(new FileWriter(f));
                output.write(s1);
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
    
            }
        }
    
    }
    FileOperation

    发请求

    HttpClientUtil

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})
    public class HttpClientUtil {
        private String excelUrl = "C:\Users\hasee\Documents\263EM\108251@ycgwl.com\receive_file\aa.xls";
        @Autowired
        private IPpApiService ppApiService;
        @Autowired
        private IBaseRedisCacheService baseRedisCacheService;
        private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    
    
        private static final int TIMEOUT = 5 * 1000000;//5 * 1000
    
        //            StringUtils.strToInteger(propFactory.getConfig("max_http_connection"), 50);// 50
        private static final int MAX_HTTP_CONNECTION = 50;
    
    
        private static final int MAX_CONNECTION_PER_HOST = 10;// 10
    
        private static final String CHARSET_UTF8 = "UTF-8";
    
        private static HttpClientUtil instance = null;
    
        private static final String APP_KEY = "BOS";
    
        private static final String APP_SECRET = "WREW223421FDR134R";
    
        //  private static Logger logger = Logger.getLogger(HttpClientUtil.class);
    
        static {
    
            //HttpClient 连接池属性设置,HOST并发数默认为50, 客户端总并发数为200, TimeOut时间为5s.
    
            HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();
    
            // 文档参数说明:Sets the maximum number of connections allowed.
            httpConnectionManagerParams.setMaxTotalConnections(MAX_HTTP_CONNECTION);
    
            // 文档参数说明: Sets the default maximum number of connections allowed for a given host config.
            httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(MAX_CONNECTION_PER_HOST);
    
            // 读取数据超时时间
            httpConnectionManagerParams.setSoTimeout(TIMEOUT);
    
            // 连接超时时间
            httpConnectionManagerParams.setConnectionTimeout(TIMEOUT);
    
            connectionManager.setParams(httpConnectionManagerParams);
    
        }
    
        public HttpClientUtil() {
    
        }
    
        public static HttpClientUtil getInstance() {
    
            if (null == instance) {
    
                synchronized (HttpClientUtil.class) {
    
                    if (instance == null) {
    
                        instance = new HttpClientUtil();
    
                    }
    
                }
    
            }
    
            return instance;
    
        }
    
        public HttpClient createHttpClient() {
    
            HttpClient httpClient = new HttpClient(connectionManager);
    
            return httpClient;
    
        }
    
        /**
         * 进行 http请求返回String结果
         *
         * @param url
         * @return
         */
    
        public String getHttpClientJson(String url) {
    
            HttpClient httpClient = createHttpClient();
    
            GetMethod getMethod = new GetMethod(url);
    
            try {
    
                httpClient.executeMethod(getMethod);
    
                InputStreamReader in = new InputStreamReader(getMethod.getResponseBodyAsStream(),
                        HttpClientUtil.CHARSET_UTF8);
                //            String jsonString = getMethod.getResponseBodyAsString();
                String jsonString = getStringByParams(in);
    
                return jsonString;
    
            } catch (Exception e) {
                 /*   logger.error("Http Client GetMethod Execute is Exception , Message = " + e.getMessage(), e);*/
                return "{"msg":"获取账户余额信息失败!","success":"false"}";
            } finally {
                if (getMethod != null)
                    getMethod.releaseConnection();
    
            }
    
        }
    
        /**
         * 进行 http post请求返回String结果
         *
         * @param url
         * @return
         */
    
        public String postHttpClientJson(String url, String params) {
    
            HttpClient httpClient = createHttpClient();
    
            PostMethod postMethod = getPostMethod(url, params);
    
            try {
                //logger.info(" Request Navigate Url is : " + url);
    
                httpClient.executeMethod(postMethod);
                //            String jsonString = postMethod.getResponseBodyAsString();
                InputStreamReader in = new InputStreamReader(postMethod.getResponseBodyAsStream(),
                        HttpClientUtil.CHARSET_UTF8);
                String jsonString = getStringByParams(in);
    
                // 当地址端口错误时,返回为空,为防止Json解析异常
                if (jsonString == null || "".equals(jsonString)) {
                    jsonString = "[{"msg":"获取折扣信息失败!","success":"false"}]";
                }
    
                return jsonString;
    
            } catch (Exception e) {
                //  logger.error("Http Client PostMethod Execute is Exception , Message = " + e.getMessage(), e);
                return e.getMessage();
            } finally {
                if (postMethod != null)
                    postMethod.releaseConnection();
    
            }
    
        }
    
        /**
         * @param params
         * @return List<NameValuePair>    返回类型
         * @throws
         * @Title: getCheckParam
         * @Description: (设置验证参数)
         */
        private List<NameValuePair> getCheckParam(String params) {
            String digest = SecurityUtil.getDigest(params + APP_KEY + APP_SECRET);
            String timestamp = "" + new Date().getTime();
            final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
            // 接口调用的请求格式
            nameValueList.add(new NameValuePair("params", params));
    
            nameValueList.add(new NameValuePair(Constants.DEFAULT_ALP_DIGEST_NAME, digest));
            nameValueList.add(new NameValuePair(Constants.DEFAULT_ALP_TIMESTAMP_NAME, timestamp));
            nameValueList.add(new NameValuePair("appkey", APP_KEY));
    
            return nameValueList;
    
        }
    
        /**
         * @param url
         * @param params
         * @return PostMethod    返回类型
         * @throws
         * @Title: getPostMethod
         * @Description: (设置params参数)
         */
        private PostMethod getPostMethod(String url, String params) {
            PostMethod postMethod = new PostMethod(url);
    
            List<NameValuePair> nameValueList = getCheckParam(params);
    
            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            postMethod.setRequestBody(nameValueList.toArray(new NameValuePair[nameValueList.size()]));
            //        postMethod.addRequestHeader("Connection", "close");
    
            return postMethod;
    
        }
    
        /**
         * @param in
         * @return String    返回类型
         * @throws IOException
         * @throws
         * @Title: getStringByParams
         * @Description: (将流文件转换成字符)
         */
        private String getStringByParams(InputStreamReader in) throws IOException {
    
            BufferedReader reader = new BufferedReader(in);
    
            StringBuffer stringBuffer = new StringBuffer();
    
            String str = "";
    
            while ((str = reader.readLine()) != null) {
    
                stringBuffer.append(str);
    
            }
    
            String ts = stringBuffer.toString();
    
            return ts;
        }
    
        public String getParams(String siteCode) {
    
            StringBuilder str = new StringBuilder();
            str.append("{");
            str.append(""siteCode":"" + siteCode + """);
            str.append("}");
    
            return str.toString();
        }
    
        @Test
        public void test0(){
    
        }
    
        @Test
        public void test() throws Exception {
            HttpClientUtil hcu = HttpClientUtil.getInstance();
            String url2 = "http://fo.ycgwl.com/rosefinch-web/ppapi/rest/queryFreightCount.api";
            List<DiscountOrPriceEntity> list = getList();
    
            StringBuilder sb = new StringBuilder();
            for (DiscountOrPriceEntity entity : list) {
                if (entity.getSendSiteCode() != null) {
                    entity.setFromTime(new Date());
                    String params = JSON.toJSONString(entity);
    
                    String result2 = hcu.postHttpClientJson(url2, params);
                    try {
                        DiscountOrPriceReturnEntity discountOrPriceReturnEntity = JSON.parseObject(result2, DiscountOrPriceReturnEntity.class);
                        sb.append(discountOrPriceReturnEntity.getPrice()+"
    ");
                    } catch (Exception ex) {
                        sb.append(result2+"
    ");
                    }
                } else {
                    sb.append("发件网点或派件网点不存在"+"
    ");
                }
            }
            FileOperation.writeTxtFile(sb.toString(), new File("C:\Users\hasee\Documents\263EM\108251@ycgwl.com\receive_file\aa.txt"));
    
        }
        @Test
        public void testOne(){
            HttpClientUtil hcu = HttpClientUtil.getInstance();
            String url2 = "http://fo.ycgwl.com/rosefinch-web/ppapi/rest/queryFreightCount.api";
    
            DiscountOrPriceEntity entity = new DiscountOrPriceEntity();
            entity.setSendSiteCode("TMS008");
            entity.setDispatchSiteCode("Z03419");
            entity.setCalcWeight(405.0);
            entity.setFromTime(new Date());
    
            String params = JSON.toJSONString(entity);
    
            String result2 = hcu.postHttpClientJson(url2, params);
            System.out.println(result2);
        }
    
        private List<DiscountOrPriceEntity> getList() throws IOException, BiffException {
            ReadExcel readExcel = new ReadExcel(excelUrl);
            final List<String[]> strings = readExcel.readExcel();
    
            List<DiscountOrPriceEntity> discountOrPriceEntities = new ArrayList<>();
            int i = 0;
            for (String[] ary : strings) {
                if (i == 0) {
                    i++;
                    continue;
                }
                i++;
    
               /* if (i ==100) {
                    return discountOrPriceEntities;
                }*/
                DiscountOrPriceEntity entity = new DiscountOrPriceEntity();
                String sendSite = ary[2];
                String destination = ary[4];
                Double weight = Double.parseDouble(ary[9]);
    
    
                if (StringUtils.isNotEmpty(sendSite)) {
                    BaseSiteEntity baseSiteEntityNameFromCache = this.baseRedisCacheService.getBaseSiteEntityNameFromCache(sendSite);
                    if (baseSiteEntityNameFromCache == null) {
                        entity.setSendSiteCode(null);
                    } else {
                        entity.setSendSiteCode(baseSiteEntityNameFromCache.getSiteCode());
                    }
                } else {
                    entity.setSendSiteCode(null);
                }
                if (StringUtils.isNotEmpty(destination)) {
                    BaseSiteEntity baseSiteEntityNameFromCache1 = this.baseRedisCacheService.getBaseSiteEntityNameFromCache(destination);
                    if (baseSiteEntityNameFromCache1 == null) {
                        entity.setSendSiteCode(null);
                    } else {
                        entity.setDispatchSiteCode(baseSiteEntityNameFromCache1.getSiteCode());
                    }
                } else {
                    entity.setSendSiteCode(null);
                }
    
                entity.setCalcWeight(weight);
                discountOrPriceEntities.add(entity);
                System.out.println("拼装完成"+i+"个");
            }
            return discountOrPriceEntities;
        }
    }
    HttpClientUtil
  • 相关阅读:
    C++中的指针和数组
    windows系统下JDK1.6环境变量配置
    Java Reflection (JAVA反射)
    转载:cin深入分析(下) – cin的错误处理
    OpenGL总结
    OpenGL纹理
    c/C++内存分配
    转载:cin深入分析(上) – cin输入操作处理
    c++中string的用法
    OpenGL颜色
  • 原文地址:https://www.cnblogs.com/zfzf1/p/8027368.html
Copyright © 2020-2023  润新知