如何使用 Java HttpClient 库和 PHP 上传文件
问题:
A使用 HttpClient 库版本 4.0 beta2 的 Java 应用程序尝试将文件上传到运行 PHP 的 Apache 服务器,但是PHP 脚本无法识别该文件。
解决方案:
原始 Java 代码使用 FileEntity 对象来传输文件,这是不正确的。正确的方法是使用 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 脚本识别。
以上是如何使用Java的HttpClient库正确上传文件到PHP服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!