如何使用Java HttpClient库与PHP一起上传文件
如何使用Java HttpClient库与PHP一起上传文件
我想写一个Java应用程序,用于将文件上传到带有PHP的Apache服务器。Java代码使用了Jakarta HttpClient库的4.0 beta2版本:
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.FileEntity; 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:9002/upload.php"); File file = new File("c:/TRASH/zaba_1.jpg"); FileEntity reqEntity = new FileEntity(file, "binary/octet-stream"); httppost.setEntity(reqEntity); reqEntity.setContentType("binary/octet-stream"); 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文件`upload.php`非常简单:
读取响应后,我得到以下结果:
执行请求 POST http://localhost:9002/upload.php HTTP/1.1
HTTP/1.1 200 OK 可能的文件上传攻击:文件名 ''。 Array ( )
所以请求成功了,我能够与服务器通信,但是PHP没有注意到文件 - 方法`is_uploaded_file`返回了`false`,而`$_FILES`变量为空。我不知道为什么会发生这种情况。我已经追踪了HTTP响应和请求,它们看起来都没问题:
请求是:
POST /upload.php HTTP/1.1
Content-Length: 13091
Content-Type: binary/octet-stream
Host: localhost:9002
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.0-beta2 (java 1.5)
Expect: 100-Continue
˙Ř˙ŕ..... 剩余的二进制文件...
响应是:
HTTP/1.1 100 Continue HTTP/1.1 200 OK Date: Wed, 01 Jul 2009 06:51:57 GMT Server: Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 mod_jk/1.2.26 X-Powered-By: PHP/5.2.5 Content-Length: 51 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html 可能的文件上传攻击:文件名 ''。Array ( )
我在本地Windows XP上使用xampp和远程Linux服务器进行了测试。我还尝试使用之前的HttpClient版本 - 版本3.1 - 结果更不明确,`is_uploaded_file`返回了`false`,但`$_FILES`数组填充了正确的数据。