HttpClient實現表單提交上傳文件
本文實例為大傢分享瞭HttpClient實現表單提交上傳文件的具體代碼,供大傢參考,具體內容如下
需求:如何利用HttpClient,發起post請求,模擬表單提交,在後端上傳文件?
上傳文件接口:
/** * 文件上傳測試接口 * @return */ @PostMapping("/upload") public Object uploadFileTest(@RequestParam("file") MultipartFile file, @RequestParam("file_name") String file_name, @RequestParam("file_code") String file_code) { System.out.println(file_name+","+file_code); return "OK"; }
啟動後,可以通過postman進行調用,最後打印OK,表示接口可以調用通
然後就是正式編碼環節瞭
首先引入需要的包:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency>
編寫main方法,直接發起調用
public static String httpClientUploadFile(String url, File file) { CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; //每個post參數之間的分隔。隨意設定,隻要不會和其他的字符串重復即可。 String boundary = "--------------4585696313564699"; try { //文件名 String fileName = file.getName(); HttpPost httpPost = new HttpPost(url); //設置請求頭 httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary); //HttpEntity builder MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //字符編碼 builder.setCharset(Charset.forName("UTF-8")); //模擬瀏覽器 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setContentType(ContentType.MULTIPART_FORM_DATA); //boundary builder.setBoundary(boundary); //multipart/form-data builder.addPart("file", new FileBody(file, ContentType.DEFAULT_BINARY)); // binary //builder.addBinaryBody("name=\"file\"; filename=\"mysql.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 //其他參數 //builder.addTextBody("file_name", fileName, ContentType.create("text/plain", Consts.UTF_8)); builder.addTextBody("file_name", fileName, ContentType.MULTIPART_FORM_DATA); builder.addTextBody("file_code", "111111", ContentType.MULTIPART_FORM_DATA); //HttpEntity HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 執行提交 HttpResponse response = httpClient.execute(httpPost); //響應 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 將響應內容轉換為字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("result" + result); return result; } //main 方法 public static void main(String[] args) { httpClientUploadFile("http://127.0.0.1:8080/test/tempA/upload",new File("e:/tmp/mysql.docx")); }
最後返回OK,調用成功
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- postman模擬post請求的四種請求體
- C# HttpClient Post參數同時上傳文件的實現
- Java使用HttpClient詳細示例
- HttpClient詳細使用示例代碼
- Java HttpClient用法的示例詳解