how to copy zip and other files in REST web service using java
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).
精彩评论