用httpclient4.3 post方式推送文件到服務端
準備:httpclient-4.3.3.jar;httpcore-4.3.2.jar;httpmime-4.3.3.jar
/**
* 上傳文件
* @throws ParseException
* @throws IOException
*/
publicstaticvoidpostFile()throwsParseException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
// 要上傳的文件的路徑
String filePath =newString("F:/pic/001.jpg");
// 把一個普通參數和文件上傳給下面這個地址 是一個servlet
HttpPost httpPost =newHttpPost(
"http://localhost:8080/xxx/xxx.action");
// 把文件轉換成流對象FileBody
File file =newFile(filePath);
FileBody bin =newFileBody(file);
StringBody uploadFileName =newStringBody(
"把我修改爲文件名稱", 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
* @param destFileName xxx.jpg/xxx.png/xxx.txt
* @throws ClientProtocolException
* @throws IOException
*/
publicstaticvoidgetFile(String url, String destFileName)
throwsClientProtocolException, IOException {
// 生成一個httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget =newHttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
File file =newFile(destFileName);
try{
FileOutputStream fout =newFileOutputStream(file);
intl = -1;
byte[] tmp =newbyte[1024];
while((l = in.read(tmp)) != -1) {
fout.write(tmp,0, l);
// 注意這裏若是用OutputStream.write(buff)的話,圖片會失真,你們能夠試試
}
fout.flush();
fout.close();
}finally{
// 關閉低層流。
in.close();
}
httpclient.close();
}