利用 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中文网其他相关文章!