packagecn.hkwl.lm.util;importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importjava.util.Iterator;importjava.util.Map;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.mime.FormBodyPart;importorg.apache.http.entity.mime.MultipartEntity;importorg.apache.http.entity.mime.content.FileBody;importorg.apache.http.entity.mime.content.StringBody;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;public classUploadToServer {private static final Logger log = LoggerFactory.getLogger(UploadToServer.class);public static String postFile(String url,Map param, File file) throwsClientProtocolException, IOException {
String res= null;
CloseableHttpClient httpClient=HttpClients.createDefault();
HttpPost httppost= newHttpPost(url);
httppost.setEntity(getMutipartEntry(param,file));
CloseableHttpResponse response=httpClient.execute(httppost);
HttpEntity entity=response.getEntity();if (response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) {
res= EntityUtils.toString(entity, "UTF-8");
response.close();
}else{
res= EntityUtils.toString(entity, "UTF-8");
response.close();throw newIllegalArgumentException(res);
}returnres;
}private static MultipartEntity getMutipartEntry(Map param, File file) throwsUnsupportedEncodingException {if (file == null) {throw new IllegalArgumentException("文件不能为空");
}
FileBody fileBody= newFileBody(file);
FormBodyPart filePart= new FormBodyPart("file", fileBody);
MultipartEntity multipartEntity= newMultipartEntity();
multipartEntity.addPart(filePart);
Iterator iterator =param.keySet().iterator();while(iterator.hasNext()) {
String key=iterator.next();
FormBodyPart field= new FormBodyPart(key, newStringBody((String) param.get(key)));
multipartEntity.addPart(field);
}returnmultipartEntity;
}
}