帶有PHP 檔案上傳功能的Java HttpClient
在本文中,我們將探討如何利用Java HttpClient 庫版本4.0 beta2 上傳檔案到運行PHP 的Apache 伺服器。
場景和問題
開發人員旨在透過 Jakarta HttpClient 函式庫將檔案從 Java 傳輸到 PHP。但是,在執行請求時,PHP 伺服器不會偵測到上傳的檔案。 is_uploaded_file() 函數傳回 false,且 $_FILES 變數保持為空。
解決方案
要修正這個問題,我們需要修改 Java 程式碼。該問題源自於 FileEntity 的錯誤使用。這是修正後的程式碼:
import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.EntityUtils; public class PostFile { public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost("http://localhost:9001/upload.php"); File file = new File("c:/TRASH/zaba_1.jpg"); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, "image/jpeg"); mpEntity.addPart("userfile", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println(EntityUtils.toString(resEntity)); } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } }
關鍵的變更是使用 MultipartEntity 而不是 FileEntity。這允許我們將文件作為多部分錶單資料請求發送,這是 PHP 檔案上傳的預期格式。
以上是如何正確地將檔案從 Java HttpClient 上傳到 PHP 伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!