import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.*; import org.apache.http.impl.client.*; import org.apache.http.util.EntityUtils; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; public class UploadTest { @Test public void test(){ } public void upload(String localFile){ CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); // 把一个普通参数和文件上传给下面这个地址 是一个servlet HttpPost httpPost = new HttpPost("http://epcf.chfcloud.com:8081/epc/epc-tenant/tenant/masterValue/import"); httpPost.addHeader("Cookie", "JSESSIONID=41504D4F245D0B9F0F034E5BADB171AD; fingerprint=7fc9d031a5d3fbde7343392257c4268c; bfd_g=undefined; bfd_g=undefined; serviceId=eLU6xd2nmuk%3D; tenantID=qa4vwpIh+Mus2Pjiu09LAg%3D%3D; Language=Iq8Sdc%2BYWYk%3D; permType=P7Q4CSsApuw%3D; tma=241884240.33854200.1557119272151.1557292553911.1557365279225.4; token=BPG3hF9UWNmO7OBRpjNp0oENWJgfCHvM%2B58djIgshLh%2BQigidzZmwA%3D%3D; openId=ydEWUiJPrfVJCuAHnqAw7H5CKCJ3NmbA; userName=efSfn2jNU4JRlAosdzDuHw%3D%3D; tenantId=r6pkH34cVxMTQfifA2D6wg%3D%3D; companyId=QmvgZmMzI4U%3D; companyMasterId=moNwga7f%2FaA%3D; tmc=1.241884240.84620408.1557384141104.1557384141104.1557384141104; tmd=35.241884240.33854200.1557119272151."); // 把文件转换成流对象FileBody FileBody bin = new FileBody(new File(localFile)); StringBody defineCode = new StringBody("N111", ContentType.create( "text/plain", Consts.UTF_8)); // StringBody password = new StringBody("123456", ContentType.create( // "text/plain", Consts.UTF_8)); HttpEntity reqEntity = MultipartEntityBuilder.create() // 相当于 .addPart("file", bin) // 相当于 .addPart("defineCode", defineCode) // .addPart("pass", password) .build(); httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应 response = httpClient.execute(httpPost); System.out.println("The response value of token:" + response.getFirstHeader("token")); // 获取响应对象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // 打印响应长度 System.out.println("Response content length: " + resEntity.getContentLength()); // 打印响应内容 System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8"))); } // 销毁 EntityUtils.consume(resEntity); }catch (Exception e){ e.printStackTrace(); }finally { try { if(response != null){ response.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(httpClient != null){ httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } } }