开发者

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 fil开发者_如何学Goe 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜