有谁知道如何使用 java 在 REST Web 服务中复制 zip 文件、jar 文件、二进制文件和其他文件中的数据?我编写了一个 Web 服务方法来使用 FileInputStream 复制文件,但它只能复制文件类型。
谢谢
有谁知道如何使用 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 请求下载任何内容(在更改“接受”标头之后)。