![](/img/trans.png)
[英]how to download different type of files in rest web service using java
[英]how to copy zip and other files in REST web service using java
有谁知道如何使用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”标头后)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.