Httpclient 4.x文件上傳
依賴jar包:httpclient-4.4.jar、httpcore-4.4.jar、httpmime-4.4.x.jar
</div>
[Java]代碼
/**
* httpclient4.x 文件上傳
*
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) {
String url = "http://localhost:8080/fileRequest";
File file = new File("/home/opt/fileUpload/A.zip");
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//others param for request
StringBody stringFileNameBody = new StringBody("fileName", ContentType.create("text/plain", "UTF-8"));
builder.addPart(name, stringFileNameBody);
StringBody stringFileMd5 = new StringBody("md5", ContentType.create("text/plain", "UTF-8"));
builder.addPart(name, stringFileMd5);
//file param for request
String fileRequestParam = "file";
FileBody fileBody = new FileBody(file, ContentType.create("multipart/form-data", "UTF-8"));
builder.addPart(fileRequestParam, fileBody);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} catch(Exception e){
e.printStackTrace();
}finally {
try {
EntityUtils.consume(resEntity);
} catch (IOException e) {
e.printStackTrace();
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} 本文由用戶 RegPoate 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!