依赖jar包:httpclient-4.4.jar、httpcore-4.4.jar、httpmime-4.4.x.jar
/** * 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(); } } } } }