通过调用支付宝查询对账单接口返回bill_download_url下载zip,解压缩

摘要:
通过url下载zip语句文件并解压。bizType=trade&userId=20889117596609430156&fileType=csv。zip&bizDates=2070628&downloadFileName=200889117596609430156_2070628.csv.zip&fileId=%2Ftrade%2F2088911759609430156%2F20170628.csv。zip&timestamp=1499075857&token=fdcd1fa66d4270ff19f727db0db7af70“;Stringfilename=getDownloadFileName;Stringdown_url=”d:\test\chshi123\“+filename+”。Zip“;/**通过调用从支付宝接口返回的url下载Zip文件*/poolandown_success=downLoadZip;Stringconnell=”“;//trueorfalse下载成功,如果{Filesave_down_url=newFile;/**解压缩下载的zip文件*//StringunzipFilePath=comZipCvsFile;/**读取下载的zip文件并返回字符串*/conmetall=readZipToString;}/*返回的结果为*1.false,下载失败*2.空字符串||“false”。解压缩或读取字符串转换失败*///returnconmetall;}/***通过从支付宝查询语句界面返回的url下载zip文件*@paramalipay _ url*@paramdown_url*@return*/publicstaticbooleandownLoadZip{booleandown_success=false;intbytsum=0;intbytesread=0;Datedate=newDate();SimpleDateFormatsf=newSimpleDateFormat;StringdateFloder=sf.format;InputStreaminStream=null;FileOutputStreamfs=null;try{URLurl=newURL;URLConnectionconn=url.openConnection();inStream=conn.getInputStream();//自定义文件保存地址StringunzipFilePath=down_url.substring;//判断下载和保存路径文件夹FileunzipFile Dir=newFile//下载文件存储地址if(!UnzipFileDir.isDirecty()){UnzipFileDir.mkdirs();}//提取的文件是否已存在FileentryFile=newFile;如果{//删除现有目标文件entryFile.Delete();}fs=新文件输出流;byte[]缓冲区=新字节[4028];while((byteread=inStream.read(缓冲区))!

通过url下载zip对账单文件,进行解压。

读取压缩文件内容

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;

import java.text.SimpleDateFormat;

import java.util.Date;

import com.alipay.downOrdession.*;//修改zip源码包



public class Zip2String {
	
    public static void main(String[] args) throws Exception {
    	String alipay_url = 
"http://dwbillcenter.alipay.com/downloadBillFile.resource?bizType=trade&userId=20889117596609430156&fileType=csv.zip&bizDates=20170628&downloadFileName=20889117596609430156_20170628.csv.zip&fileId=%2Ftrade%2F20889117596609430156%2F20170628.csv.zip&timestamp=1499075857&token=fdcd1fa66d4270ff19f727db0db7af70";
        String filename=getDownloadFileName(alipay_url);
        
        String down_url = "d:\test\ceshi123\"+filename+".zip";
        /*
    	 * 通过调用支付宝接口返回的url下载zip文件
    	 */
        boolean down_success = downLoadZip(alipay_url,down_url);
        String connetall = "";
        
        //true or  false 下载成功,调用解压方法
        if(down_success){
        	File save_down_url = new File(down_url);
        	/*
        	 * 解压下载的zip文件
        	 */
//        	String unzipFilePath = comZipCvsFile(save_down_url);
        	
        	/*
        	 * 读取下载的zip文件,返回一个string字符串
        	 */
        	connetall = readZipToString(save_down_url);
        }
        /* 返回结果
         * 1.false,下载失败
         * 2.空字符串||"false"。解压或者读取转string失败
         */
        //return connetall;
    }

    /**
     * 通过支付宝查询对账单接口返回的url,下载zip文件
     * @param alipay_url
     * @param down_url
     * @return
     */
    public static boolean downLoadZip(String alipay_url,String down_url) {
    	boolean down_success = false;
        int bytesum = 0;
        int byteread = 0;
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        String dateFloder = sf.format(date);

        InputStream inStream = null;
        FileOutputStream fs = null;
        
        try {
          
        	URL url = new URL(alipay_url);
            URLConnection conn = url.openConnection();
            inStream = conn.getInputStream();
            
        	//自定义文件保存地址
        	String unzipFilePath =  down_url.substring(0, down_url.lastIndexOf("\"));//判断下载保存路径文件夹
        	
            File unzipFileDir = new File(unzipFilePath);//下载文件存放地址
            if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
                unzipFileDir.mkdirs();
            }
            //解压文件是否已存在
            File entryFile = new File(down_url);
            if (entryFile.exists()) {
            	//删除已存在的目标文件 
                entryFile.delete();
            }
            
            fs = new FileOutputStream(down_url);

            byte[] buffer = new byte[4028];

            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            down_success = true;
            System.out.println(dateFloder+"文件下载成功.....");
        } catch (Exception e) {
            System.out.println(dateFloder+"文件下载失敗" + e);

            return false;
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                inStream = null;
            }

            try {
                if (fs != null) {
                    fs.close();
                }
            } catch (IOException e) {
                fs = null;
            }
        }
        return down_success;
    }
    
    
    
    /** 
     * 读取zip文件,不解压缩直接解析,支持文件名中文,解决内容乱码 
     * @param file 
     * @return   读取zip文件,返回字符串
     * @throws Exception 
     */  
    @SuppressWarnings("unchecked")  
    public static  String readZipToString(File file) throws Exception {
    	String connet = "";
       try {
		
    	   //获得输入流,文件为zip格式,  
           //支付宝提供  
           //20886126836996110156_20160906.csv.zip内包含  
           //20886126836996110156_20160906_业务明细.csv  
           //20886126836996110156_20160906_业务明细(汇总).csv  
           ZipInputStream in = new ZipInputStream(new FileInputStream(file));  
           //不解压直接读取,加上gbk解决乱码问题  
           BufferedReader br = new BufferedReader(new InputStreamReader(in,"gbk"));   
           ZipEntry zipFile;
           //返回的字符串---每个文件内容相加
           BufferedWriter bw = null;
           //循环读取zip中的cvs文件,无法使用jdk自带,因为文件名中有中文  
           while ((zipFile=in.getNextEntry())!=null) {
               if (zipFile.isDirectory()){
                   //如果是目录,不处理  
               }
               String file_connet = "";
               //获得cvs名字  
               String fileName = zipFile.getName();
               System.out.println("-----"+fileName);
               //检测文件是否存在  
               if (fileName != null && fileName.indexOf(".") != -1) {
                    String line;
                    /*
                     * 1.每一行用 | 隔开
                     * 2.每一个文件用 ; 隔开
                     */
                  //  bw = new BufferedWriter(new FileWriter("d:\test\test.txt")); //测试读取内容
                    while ((line = br.readLine()) != null) {
                   	 
                   	 file_connet = file_connet + "|" + line;
                       // System.out.println(line);
                   	 
                    }    
               }
               
               connet = connet + file_connet + ";";
           }
         //  bw.write(connet);
           //关闭流  
         //  bw.close();
           br.close();  
           in.close();
    	   
    	   
	} catch (Exception e) {
		System.out.println("zip文件读取失敗" + e);

         return "false";
	}
        
	return connet;
    }
    
    
    
    /**解压缩 
     * 解压通过url获得对账单数据流(.zip)
     * @param file //zip文件存放地址
     * @return 
     */  
    @SuppressWarnings("unchecked")
    public static String comZipCvsFile(File file) throws Exception {
    	//自定义文件保存地址
    	String unzipFilePath = file.getCanonicalPath();
    	unzipFilePath = unzipFilePath.substring(0, unzipFilePath.lastIndexOf("."));
    	System.out.println("解压后文件保存路径:"+unzipFilePath);
    	
        //获得输入流,文件为zip格式,
        //支付宝提供  
        //20886126836996110156_20160906.csv.zip内包含  
        //20886126836996110156_20160906_业务明细.csv  
        //20886126836996110156_20160906_业务明细(汇总).csv   
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry zipFile;
        BufferedOutputStream bos = null;
        try {
			
        	zin = new ZipInputStream(new FileInputStream(file));

            while ((zipFile = zin.getNextEntry()) != null) {
                System.out.println(zipFile.getName());

                File target = new File(file.getParent(), zipFile.getName());

                if (!target.getParentFile().exists()) {
                	// 创建文件父目录
                    target.getParentFile().mkdirs();
                }

               //创建解压缩文件保存的路径 文件夹
                File unzipFileDir = new File(unzipFilePath);//解压文件存放地址---unzipFilePath(解压文件去吃.zip)
                if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
                    unzipFileDir.mkdirs();
                }

              
                String file_Name_csv = target.getName();
                String entryFilePath = unzipFilePath + File.separator + file_Name_csv;//decom_Path(存放地址)+文件名

                //解压文件是否已存在
                File entryFile = new File(entryFilePath);
                if (entryFile.exists()) {
                	//删除已存在的目标文件 
                    entryFile.delete();
                }

                /*
                 * 写入文件
                 */
//              bos = new BufferedOutputStream(new FileOutputStream(target));//解压到和zip在同一个文件夹
                bos = new BufferedOutputStream(new FileOutputStream(entryFile));//自定义文件夹

                int read = 0;
                byte[] buffer = new byte[1024 * 10];

                while ((read = zin.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, read);
                }

                bos.flush();
            }
            //关闭流
            zin.close();
            bos.close();
        	
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("zip文件解压失敗" + e);

            return "false";
		}
		return unzipFilePath;//返回解压文件保存路径
        
    }
    
    
    /**
     * 通过alipay_url获取下载的文件名称
     * @param alipay_url
     * @return
     */
    private static String getDownloadFileName(String alipay_url){  
        String tempStr = alipay_url.substring(alipay_url.indexOf("downloadFileName")+17, alipay_url.length());  
        tempStr = tempStr.substring(0,tempStr.indexOf(".zip"));  
        return tempStr;  
    }
    
}

百度网盘下载地址   http://pan.baidu.com/s/1jHRSaUU

免责声明:文章转载自《通过调用支付宝查询对账单接口返回bill_download_url下载zip,解压缩》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇kali学习笔记(一):虚拟机安装好kali后应进行的配置md /mdd /ml /mt/mtd下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

HSF处理流程分析

一.HSF的基本概念 HSF全称为High-Speed Service Framework,旨在为淘系的应用提供一个分布式的服务框架,HSF从分布式应用层面以及统一的发布/调用方式层面为大家提供支持,从而可以很容易的开发分布式的应用以及提供或使用公用功能模块,而不用考虑分布式领域中的各种细节技术,例如远程通讯、性能损耗、调用的透明化、同步/异步调用方式的实...

接口测试中抓包工具的使用

在被测接口并没有明确的接口文档给出时,我们需要借助抓包工具来帮助测试,利用抓包工具我们几乎可以获得接口文档中能给你的一切。常见的抓包工具有Charles和Fiddler, Fiddler只能用在Windows平台, 而Charles可用于Windows, Mac, IOS和Android多平台。下面就总结一下Charles的用法。 一、Web抓取   Ch...

service和serviceImpl的选择

同行中,有些同行公司的代码风格是service层=service接口+serviceImpl实现类; 而有的同行公司的代码风格是service层=service类; 为什么不一样呢? 以前没想过这个问题,今天突然对这个产生了疑惑,通过百度,和github及朋友处以及自己的思考,有了如下结论: 当项目的业务逻辑简单时,可选择service层=service类...

获取到集成指定类,接口等的类

利用反射获取到实现当前接口的类, 本文只做代码验证,无任何实际意义 具体代码如下 1 namespace General.Cons 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 //假设从接...

Java设计模式7:适配器模式

适配器模式 适配器模式说的是,可以把一个类的接口变换成客户端所期待的另一种接口,使得原本因接口不匹配而无法在一起工作的两个类可以一起工作。 适配器模式的用途 适配器模式的用途,在网上找了一幅图,挺形象的: 比方说我有一个台灯,其插头是标准的两相的交流电插头,即阳极、阴极。我旅游到了一个地方想用自己的台灯,但发现旅馆里面只有三相的插头,即在阳极、阴极的基础...

微信公众号--JS-SDK

JS-SDK 微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。 通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。 JS-SDK使用步骤 l  步骤一:绑定域名 先登录微信公众平台进...