利用FileUpload 取代已棄用的org.apache.http.entity.FileEntity
Android 6 中已棄用org.apache. http需要探索文件上傳的替代方法。雖然 HttpURLConnection 提供了一種解決方法,但其複雜性可能令人望而生畏。
更有效的解決方案是利用 FileUpload 類,如以下程式碼片段所示:
// Instantiate the HttpURLConnection URL url = new URL(server_url); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Set connection properties httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); // Create a FileUpload instance String boundary = UUID.randomUUID().toString(); FileUpload fileUpload = new FileUpload(); // Add file to FileUpload FileInputStream fileInputStream = new FileInputStream(file); fileUpload.addFilePart("image", file.getName(), fileInputStream, "image/png"); // Set connection headers httpURLConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Write to connection fileUpload.write(httpURLConnection.getOutputStream()); // Read response if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Process response } else { // Handle errors } // Close connection httpURLConnection.disconnect();
透過使用 FileUpload,您可以簡化檔案上傳過程,而不會過於複雜。
以上是FileUpload 如何取代 Android 檔案上傳中已棄用的 org.apache.http.entity.FileEntity?的詳細內容。更多資訊請關注PHP中文網其他相關文章!