简体   繁体   中英

how to copy zip and other files in REST web service using java


Do anyone know how to copy data in zip file, jar file , binary file and others in REST web service using java? I write a web service method to copy file using FileInputStream , but it can only copy file type.

thanks

I'd recommend using apache httpclient for this. Your code might look something like (note, make sure you're using version 4.x or higher):

HttpClient client = new DefaultHttpClient();
HttpRequestBase httpMethod = httpMethod = new HttpGet(myUrlString);
httpMethod.setHeader("Accept", "application/zip");
HttpResponse response = httpClient.execute(httpMethod);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != 200) {
    throw new Exception("Bad return status code of: "+statusCode);
}
HttpEntity entity = response.getEntity();
if( entity != null) {
    FileOutputStream fos = new FileOutputStream("myFile.zip");
    int nextByte=0;
    InputStream cis = entity.getContent();
    try {
        while( (nextByte = cis.read()) >= 0) fos.write(nextByte);
    } finally {
        fos.close();
        cis.close();
    }
}

I haven't compiled this, but you could probably get it going without too much issue (feel free to edit my comment and correct the code if you try to compile this and there are errors). Also note, this code should generically work for downloading anything from a web request (after changing the "Accept" header).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM