轉自:http://www.oschina.net/code/snippet_216580_38020
基於HttpClient 4.3.3 的一個上傳、下載文件的例子,特轉載以供大家學習參考。
/**
* 上傳文件
* @throws ParseException
* @throws IOException
*/
public static void postFile() throws ParseException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 要上傳的文件的路徑
String filePath = new String("F:/pic/001.jpg");
// 把一個普通參數和文件上傳給下面這個地址 是一個servlet
HttpPost httpPost = new HttpPost(
"http://localhost:8080/xxx/xxx.action");
// 把文件轉換成流對象FileBody
File file = new File(filePath);
FileBody bin = new FileBody(file);
StringBody uploadFileName = new StringBody(
"把我修改成文件名稱", ContentType.create(
"text/plain", Consts.UTF_8));
//以瀏覽器兼容模式運行,防止文件名亂碼。
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("uploadFile", bin) //uploadFile對應服務端類的同名屬性<File類型>
.addPart("uploadFileName", uploadFileName)//uploadFileName對應服務端類的同名屬性<String類型>
.setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);
System.out.println("發起請求的頁面地址 " + httpPost.getRequestLine());
// 發起請求 並返回請求的響應
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println("----------------------------------------");
// 打印響應狀態
System.out.println(response.getStatusLine());
// 獲取響應對象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印響應長度
System.out.println("Response content length: "
+ resEntity.getContentLength());
// 打印響應內容
System.out.println(EntityUtils.toString(resEntity,
Charset.forName("UTF-8")));
}
// 銷燬
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
/**
* 下載文件
* @param url http://www.xxx.com/img/333.jpg
* @param destFileName xxx.jpg/xxx.png/xxx.txt
* @throws ClientProtocolException
* @throws IOException
*/
public static void getFile(String url, String destFileName)
throws ClientProtocolException, IOException {
// 生成一個httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
File file = new File(destFileName);
try {
FileOutputStream fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
// 注意這裏如果用OutputStream.write(buff)的話,圖片會失真,大家可以試試
}
fout.flush();
fout.close();
} finally {
// 關閉低層流。
in.close();
}
httpclient.close();
}