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();
HttpEntity resEntity = null;
CloseableHttpResponse response = null;
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());
response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
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();
}
}
}
}
网友评论