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