public void inputStreamUpload() { //創建HttpClient對象 CloseableHttpClient client = HttpClients.createDefault(); //構建POST請求 請求地址請更換為自己的。 //1) HttpPost post = new HttpPost("http://localhost:8003/uploadAndDownload/uploadFileAction"); InputStream inputStream = null; try { //文件路徑請換成自己的 //2) inputStream = new FileInputStream("G:\\LearnVideo\\text01.txt"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //第一個參數為 相當於 Form表單提交的file框的name值 第二個參數就是我們要發送的InputStream對象了 //第三個參數是文件名 //3) builder.addBinaryBody("uploadFile", inputStream, ContentType.create("multipart/form-data"), "text01.txt"); //4)構建請求參數 普通表單項 StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA); builder.addPart("id",stringBody); HttpEntity entity = builder.build(); post.setEntity(entity); //發送請求 HttpResponse response = client.execute(post); entity = response.getEntity(); if (entity != null) { inputStream = entity.getContent(); //轉換為字節輸入流 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8)); String body = null; while ((body = br.readLine()) != null) { System.out.println(body); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } 分享到: 閱讀更多 JAVA熊 的文章 關鍵字: 技術