使用 Java HttpClient 和 PHP 上传文件
尝试使用 Java HttpClient 库版本 4.0 将文件上传到 PHP 的 Apache 服务器时beta2 出现 PHP 脚本无法检测到 Java 上传的文件的问题application.
在给定的 Java 代码片段中,错误在于使用 FileEntity 来封装文件数据。下面更正后的 Java 类使用 MultipartEntity,这对于 multipart/form-data 上传至关重要:
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(); } }
此更正可确保文件正确上传,并且 PHP 脚本的 is_uploaded_file() 方法应返回 true文件传输成功后,如预期。
以上是为什么我的 Java HttpClient 文件上传到 PHP 失败,如何使用 MultipartEntity 修复它?的详细内容。更多信息请关注PHP中文网其他相关文章!