import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class FileUpload { public static void main(String[] args) throws Exception { FileUpload fileupload=new FileUpload(); String LoginUrl = "";// 登录地址,get请求,所以这里面带了账号和密码 String UploadUrl = "";// 上传文件地址 String FileUrl ="";// 所要上传的文件夹 fileupload.GetCookies(LoginUrl); fileupload.UploadFile(UploadUrl, FileUrl); } private static BasicCookieStore cookieStore = new BasicCookieStore(); private static CloseableHttpClient httpClient = HttpClients.custom() .setDefaultCookieStore(cookieStore).build(); // 登录请求Get,得到cookie。如果是post请求,把账号和密码配置成表单参数, public void GetCookies(String urlstr) throws Exception { HttpGet httpget = new HttpGet(urlstr); httpClient.execute(httpget); } //文件上传请求,POST public void UploadFile(String Url, String sqlitPath) throws IOException { try { HttpPost httpPost = new HttpPost(Url); File root = new File(sqlitPath); File[] files = root.listFiles(); for (File file : files) { String FilePath = file.getAbsolutePath(); HttpEntity reqEntity = makeMultipartEntity(FilePath); httpPost.setEntity((org.apache.http.HttpEntity) reqEntity); httpClient.execute(httpPost); } } finally { httpClient.close(); } } // 配置文件上传参数 public HttpEntity makeMultipartEntity(String sqlitPath) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); NameValuePair pair1 = new BasicNameValuePair("", ""); NameValuePair pair2 = new BasicNameValuePair("", ""); ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(pair1); pairs.add(pair2); if (pairs != null && pairs.size() > 0) { for (NameValuePair p : pairs) { builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8")); } } FileBody bin = new FileBody(new File(sqlitPath)); builder.addPart("upload", bin); return builder.build(); } }