我已经设置了一个 Apache 服务器,运行一个 php 脚本来处理各种发布请求。脚本如下所示:
$uploaddir = realpath('mypath');
//realpath('./') . '/';
$uploadfile = $uploaddir . '/' . basename($_FILES['file_contents']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
echo "\n<hr />\n";
print_r($_POST);
print "</pr" . "e>\n";
这很好用,它处理请求并将我的文件移动到我想要的位置。
但是,当我使用以下 java 客户端尝试此操作时,我什么也没得到:
String URL = "http://localhost/accept.php";
File file = new File("C:/Ozer/ANPRProject/MDT/Export/test.txt");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try{
System.out.println(""+file.exists());
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file),-1);
reqEntity.setContentType("application/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
System.out.println("execute request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
} catch(Exception e) {
} finally {
httpclient.getConnectionManager().shutdown();
}
}
我得到的系统输出是:
true
execute request POST http://localhost/accept.php HTTP/1.1
----------------------------------------
HTTP/1.1 200 OK
Response content length: 330
Chunked: false
我觉得很奇怪,因为分块尚未设置为真?虽然我在我的代码中特别要求它。但无论如何,上传不起作用。我已将 contentType 设置为“application/octet-stream”,因为我用来请求帖子的 php 脚本给了我反馈:[type] => application/octet-stream
所以 apache 的日志显示连接成功,他确实收到了请求:
127.0.0.1 - - [08/Aug/2013:16:10:04 +0200] "POST /accept.php HTTP/1.1" 200 330 "-" ""Apache-HttpClient/4.2.5 (java 1.5)"
这是我使用我的 PHP 脚本请求帖子时得到的:
127.0.0.1 - - [08/Aug/2013:15:54:23 +0200] "POST /accept.php HTTP/1.1" 200 419 "-" "-" ::1 - - [08/Aug/2013:15:54:23 +0200] "GET /testSendDat.php HTTP/1.1" 200 3330 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"
来自 php 脚本的错误日志显示:
[08-Aug-2013 16:10:04 Europe/Berlin] PHP Notice: Undefined index: file_contents
所以我知道这意味着什么,我试图从中读取文件的数组是空的。但为什么?我没有任何线索。我猜我使用错误的方式发布请求,但现在已经寻找了一段时间,并没有真正成功地找到问题所在。帮助将是非常有义务的。
哦,设置一个 apache tomcat 服务器并使用 httpservlets 会更容易吗?还是那不重要?