Download files from the server via the Java WebService interface

Source: Internet
Author: User

First, preface

This article describes how to download files, reports, and clients from the server through the WebService interface. Applies to cross-system file interaction, the transfer of files is small (control within hundreds of m). In this case, an FTP environment is built, which increases the complexity of the system deployment and the interface of the system exposed externally. It is easier to return bytes to the client by reading the file on the server.
The following is a restful interface that meets the SOA architecture interface requirements. The following code is copied to eclipse to run and function self-test runs normally. The server and client of the sample code run on the same PC and run on different PCs to change the IP address of the Publishing service and the requesting service.

Second, the Environment preparation

2.1 CXF Component: A Java-side open source component for publishing WebService services, with internal jetty web containers. Baidu official website download.
2.2 Eclipse:java Development IDE.

Third, the file download server Development 3.1 New server-side Java project, import the cxf lib directory of the jar package. 3.2 Defines a restful WebService interface for downloading files.
/** * Download report file WebService interface for multiple transfers of files larger than 20M. This does not read the file cache first, and then return in batches; * Instead of re-reading the file every time, the purpose is to make the service stateless and able to resolve the service reliability * and load balancing problems by Ngnix the reverse proxy multiple instances. There is a risk that if a file is modified or deleted during the batch transfer process, the file read failure will occur. * * @author Elon * @version 1.0 2015-06-30 * *@Path("/downloadfilews") Public  class downloadfilews {           //single-pass maximum bytes 20M.     Private Final Static intMaxsize_once;Static{maxsize_once =1024x768*1024x768* -; }/** * Download the file.     The read file content is converted to a stream of bytes, which is more than 10M. * @param req Request parameter * @return Download Response */    @POST    @Path("/downloadfile") PublicDownloadfileresponsevoDownloadFile(Downloadfilerequestvo req) {Try{returnReadfilebyte (req); }Catch(IOException e)            {E.printstacktrace (); Downloadfileresponsevo vo =NewDownloadfileresponsevo (); Vo.seterrcode (downloaderrcodeenum.read_file_exception);returnVo }    }/** * Read file contents, build file Byte stream return object.     * @param req Request parameter * @return Read the file return value. * @throws ioexception IO exception */    PrivateDownloadfileresponsevoReadfilebyte(Downloadfilerequestvo req)throwsIOException {Downloadfileresponsevo Vo =NewDownloadfileresponsevo ();//Get a decision on the last modified time of the fileFile FileObject =NewFile (Req.getfilepath ());Final LongFilelastmodifiedtime = Fileobject.lastmodified ();//Determine if files are modified during batch transfer        if(Filelastmodifiedtime! = Req.getfilelastmodifiedtime () && req.getfilelastmodifiedtime ()! =-1) {Vo.seterrcode (downloaderrcodeenum.file_has_modified_while_download);returnVo }//Read file byte stream. Bytearrayoutputstream FileStream =NewBytearrayoutputstream (1024x768); FileInputStream file =NewFileInputStream (Req.getfilepath ());byte[] Readbuff =New byte[1024x768]; while(File.read (readbuff)! =-1) {filestream.write (Readbuff); } file.close ();//Build return file byte information. More than 20M, return only 20M at a time.         Final byte[] Filebuff = Filestream.tobytearray ();intEnd =0;if(Filebuff.length-req.getstart () > Maxsize_once)            {end = Req.getstart () + maxsize_once; Vo.seteof (false); }Else{end = Filebuff.length; Vo.seteof (true); }//Copy [Start, end] in the range of bytes to the return value. Vo.setfilebytebuff (Arrays.copyofrange (Filebuff, Req.getstart (), end));        Vo.setstart (end);        Vo.seterrcode (downloaderrcodeenum.down_load_success);        Vo.setfilelastmodifiedtime (Filelastmodifiedtime); Filestream.close ();returnVo }}
3.3 Interface using input parameters, return value, error code definition

3.3.1 Input parameter type definition

/** * Download file request parameter type. * * @author Elon * @version 1.0 2015-06-30 * *@XmlRootElement(name ="Downloadfilerequest") Public  class downloadfilerequestvo implements Serializable{    /** * Serialization encoding * /    Private Static Final LongSerialversionuid =3142085277564296839L//file path    PrivateString FilePath;//Read file data start location    Private intStart//Read file time first (used to determine whether a file has been modified during batch transfer)    Private LongFilelastmodifiedtime; Downloadfilerequestvo () {SetFilePath (""); Setstart (0); Setfilelastmodifiedtime (-1); } PublicStringGetFilePath() {returnFilePath; } Public void SetFilePath(String FilePath) { This. FilePath = FilePath; } Public int Getstart() {returnStart } Public void Setstart(intStart) { This. start = start; } Public Long Getfilelastmodifiedtime() {returnFilelastmodifiedtime; } Public void Setfilelastmodifiedtime(LongFilelastmodifiedtime) { This. filelastmodifiedtime = Filelastmodifiedtime; }@Override     PublicStringtoString() {return "FilePath:"+ FilePath +"\ n"+"Start:"+ string.valueof (start); }}

3.3.2 return value type definition

/** * File Download interface return value type * * @author Elon * @version 1.0 2015-06-30 */@XmlRootElement(name ="Filevo") Public  class Downloadfileresponsevo implements Serializable{    /** * Serialization number * /    Private Static Final LongSerialversionuid =-2218217669316014388L//File byte throttle cache    Private byte[] filebytebuff;//Identifies if file transfer is complete    Private BooleanEof//Next batch read file data start location    Private intStart//Read file time first (used to determine whether a file has been modified during batch transfer)    Private LongFilelastmodifiedtime;//Error code    PrivateDownloaderrcodeenum Errcode; Public Downloadfileresponsevo() {Setfilebytebuff (NULL); Seteof (false); Setstart (0);        Seterrcode (Downloaderrcodeenum.err_code_na); Setfilelastmodifiedtime (-1); } Public byte[]Getfilebytebuff() {returnFilebytebuff; } Public void Setfilebytebuff(byte[] filebytebuff) { This. Filebytebuff = Filebytebuff; } Public Boolean isEof() {returnEof } Public void seteof(BooleanEOF) { This. EOF = EOF; } Public int Getstart() {returnStart } Public void Setstart(intStart) { This. start = start; } PublicDownloaderrcodeenumGeterrcode() {returnErrcode; } Public void Seterrcode(Downloaderrcodeenum Errcode) { This. Errcode = Errcode; } Public Long Getfilelastmodifiedtime() {returnFilelastmodifiedtime; } Public void Setfilelastmodifiedtime(LongFilelastmodifiedtime) { This. filelastmodifiedtime = Filelastmodifiedtime; }@Override     PublicStringtoString() {return "Filebytebuff:"+ filebytebuff.tostring () +"\ n"+"EOF:"+ string.valueof (EOF) +"\ n"+"Start:"+ string.valueof (start); }}

3.3.3 error Code enumeration type definition

/** * 下载文件错误码 * @author Elon * @version 1.0 2015-06-30 */publicenum DownloadErrCodeEnum {    // 下载成功    // 读取文件异常    // 在分批下载文件的过程中文件发生了修改    // 无效错误码}

3.3.4 Publishing RESTful Services

 Public classStartServer { Public Static void Main(string[] args)    {Publishws (); }Private Static void Publishws() {Jaxrsserverfactorybean Bean =NewJaxrsserverfactorybean (); Bean.setaddress ("Http://10.61.67.246:10011/download"); Bean.setservicebean (NewDownloadfilews ()); Bean.create ();//blocking threads, waiting for external message requests.          while(true)        {Try{Thread.Sleep ( the); }Catch(Interruptedexception e)            {E.printstacktrace (); }        }    }}
Iv. File Download Client Development 4.1 New Client Java project, import the jar package under the cxf Lib directory. 4.2 Call Interface download file, file byte stream write to destination file save.
 Public classstartclient { Public Static void Main(string[] args) throws IOException {downloadfileclient (); }Private Static void downloadfileclient() throws IOException {Downloadfilerequestvo req =NewDownloadfilerequestvo (); Req.setfilepath ("d:\\temp\\ test Report compressed package file. zip"); Req.setstart (0);//loop to download the file byte stream until all the contents of the file have been downloaded. FileOutputStream out=NewFileOutputStream ("D://temp/123.zip"); while(true) {WebClient WebClient = webclient.create ("http://10.61.67.246:10011"); Webclient.encoding ("UTF-8"); Response Response = Webclient.path ("Download/downloadfilews/downloadfile"). Post (req); Generictype<downloadfileresponsevo> vo =NewGenerictype<downloadfileresponsevo> () {};            Downloadfileresponsevo RSP = response.readentity (VO); Webclient.close ();if(Rsp.geterrcode ()! = downloaderrcodeenum.down_load_success) {System.err.println ("Download file err:"+ Rsp.geterrcode ()); Break; }//write a byte stream to a file             out. Write (Rsp.getfilebytebuff ());if(Rsp.iseof ()) { Break; }Else{Req.setstart (Rsp.getstart ());            Req.setfilelastmodifiedtime (Rsp.getfilelastmodifiedtime ()); }        }//output, close file        Try{ out. Flush (); out. Close (); System.err.println ("Download file success!"); }Catch(Exception e)        {E.printstacktrace (); }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Download files from the server via the Java WebService interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.