Java post文件和參數是在網絡開發中必不可少的。無論是向服務器發送數據還是獲取服務器返回的數據,我們都需要使用post方式來進行數據傳輸。Java中提供了多種方式來實現post文件和參數的傳遞,下面我們來進行一一介紹。
//使用Java原生的方式來進行post文件和參數的傳遞 URL url = new URL("http://localhost:8080/fileUpload"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); //參數部分 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("--" + boundary + "\r\n"); out.writeBytes("Content-Disposition: form-data; name=\"username\"\r\n\r\n"); out.writeBytes("Mr. John" + "\r\n"); out.flush(); //文件部分 FileInputStream fileInputStream = new FileInputStream(new File("C:/test.txt")); out.writeBytes("--" + boundary + "\r\n"); out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"); byte[] buffer = new byte[1024]; int len = 0; while ((len = fileInputStream.read(buffer)) != -1) { out.write(buffer, 0, len); } fileInputStream.close(); out.writeBytes("\r\n--" + boundary + "--\r\n"); out.flush(); //獲取服務器返回的數據 InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); inputStream.close(); connection.disconnect();
上面的代碼演示了使用Java原生的方式來進行post文件和參數的傳遞。我們根據指定的boundary來分別處理參數和文件,最后從服務器獲取返回的數據。
//使用HttpClient來進行post文件和參數的傳遞 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/fileUpload"); //參數部分 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", "Mr. John", ContentType.TEXT_PLAIN); //文件部分 File file = new File("C:/test.txt"); FileBody fileBody = new FileBody(file); builder.addPart("file", fileBody); HttpEntity httpEntity = builder.build(); httpPost.setEntity(httpEntity); CloseableHttpResponse response = httpClient.execute(httpPost); //獲取服務器返回的數據 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println(EntityUtils.toString(responseEntity)); } httpClient.close(); response.close();
上面的代碼使用了第三方庫HttpClient來進行post文件和參數的傳遞。我們使用MultipartEntityBuilder來處理參數和文件,并將其構造成HttpEntity對象。最后從服務器獲取返回的數據。
無論是使用原生的方式還是第三方庫來進行post文件和參數的傳遞,都需要注意一些細節問題,如參數和文件的命名,boundary的設置和獲取服務器返回的數據等。