简体   繁体   English

如何使用Java在REST Web服务中复制zip和其他文件

[英]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? 有谁知道如何使用Java在REST Web服务中复制zip文件,jar文件,二进制文件和其他文件中的数据? I write a web service method to copy file using FileInputStream , but it can only copy file type. 我编写了一个Web服务方法来使用FileInputStream复制文件,但是它只能复制文件类型。

thanks 谢谢

I'd recommend using apache httpclient for this. 我建议为此使用apache httpclient Your code might look something like (note, make sure you're using version 4.x or higher): 您的代码可能看起来像(请注意,请确保您使用的是4.x或更高版本):

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). 还要注意,此代码通常可以用于从Web请求下载任何内容(更改“ Accept”标头后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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