通過HttpClient4.5模擬Form表單文件上傳
阿新 • • 發佈:2018-03-31
cti main [] pmi 通過 commons finally 請求 str
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表單文件上傳