使用 Java HttpClient 和 PHP 上传文件
在此场景中,您尝试使用 Java 和 PHP 将文件上传到 Apache HttpClient 库版本 4.0 beta2。然而,尽管请求和响应看似成功,is_uploaded_file 方法返回 false,并且 $_FILES 变量仍然为空。
原因
原始 Java 代码不正确。要纠正此问题,请使用以下更新的类:
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 的使用。原来的实现缺少这个必备组件,导致PHP脚本无法识别上传的文件。
以上是尽管请求和响应成功,但为什么我的 Java HttpClient 文件上传到 PHP 却失败?的详细内容。更多信息请关注PHP中文网其他相关文章!