有谁知道如何使用java在REST Web服务中复制zip文件、jar文件、二进制文件等中的数据?我编写了一个 Web 服务方法来使用 FileInputStream 复制文件,但它只能复制文件类型。
谢谢
最佳答案
我建议使用apache httpclient为了这。您的代码可能类似于(注意,确保您使用的是 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();
}
}
我还没有编译这个,但是你可能可以在没有太多问题的情况下完成它(如果你尝试编译这个并且有错误,请随意编辑我的评论并更正代码)。另请注意,此代码通常适用于从 Web 请求下载任何内容(更改“Accept” header 后)。
关于java - 如何使用 java 在 REST Web 服务中复制 zip 和其他文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5548103/