public static void main(String[] args) { ???????CloseableHttpClient httpclient = HttpClients.createDefault(); ???????CloseableHttpResponse response = null; ???????String result = null; ???????InputStream inputStream = null; ???????try { ???????????inputStream = new FileInputStream("D:\\test.pdf"); ???????????HttpPost httpPost = new HttpPost("http://127.0.0.1/test"); ???????????MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ???????????builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ???????????builder.addBinaryBody("wj", inputStream, ContentType.create("multipart/form-data"), "test.pdf"); ???????????????????????//构建请求参数 普通表单项 ?????????????StringBody stringBody = new StringBody("100001", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("serial_no", stringBody); ???????????stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("xPosition", stringBody); ???????????stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("yPosition", stringBody); ???????????stringBody = new StringBody("2", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("sealType", stringBody); ???????????stringBody = new StringBody("1", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("paegNum", stringBody); ???????????????????????builder.setCharset(CharsetUtils.get("UTF-8")); ???????????HttpEntity entity = builder.build(); ???????????httpPost.setEntity(entity); ???????????response = httpclient.execute(httpPost); ???????????int statusCode = response.getStatusLine().getStatusCode(); ???????????System.out.println("statusCode:" + statusCode); ???????????if (statusCode == HttpStatus.SC_OK) { ???????????????HttpEntity resEntity = response.getEntity(); ???????????????result = EntityUtils.toString(resEntity, "UTF-8"); ???????????} ???????????System.out.println("result:" + result); ???????} catch (IOException ex) { ???????????Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex); ???????} finally { ???????????try { ???????????????if (null != inputStream) { ???????????????????inputStream.close(); ???????????????} ???????????} catch (IOException ex) { ???????????????Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex); ???????????} finally { ???????????????httpclient.getConnectionManager().shutdown(); ???????????} ???????} ???}
依赖包:
commons-logging-1.2.jar
httpclient-4.5.3.jar
httpcore-4.4.6.jar
httpmime-4.5.3.jar
通过HttpClient4.5模拟Form表单文件上传
原文地址:https://www.cnblogs.com/yshyee/p/8681507.html