Skip to content

Instantly share code, notes, and snippets.

@shautzin
Created April 11, 2014 10:25
Show Gist options
  • Save shautzin/10456471 to your computer and use it in GitHub Desktop.
Save shautzin/10456471 to your computer and use it in GitHub Desktop.
HttpClientRequestFile
/**
* 下载文件
* @param httpClient
* @param url
*/
public boolean httpGetFile(CloseableHttpClient httpClient, String url, java.io.File file) throws IOException {
HttpGet httpGet = createHttpGet(url);
httpGet.setHeader(HttpHeaders.USER_AGENT, Constant.USER_AGENT);
CloseableHttpResponse response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
if (entity.isStreaming()) {
try (FileOutputStream out = new FileOutputStream(file);
InputStream in = entity.getContent();
) {
byte[] buff = new byte[8096];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment