不久前我也遇到过同样的问题。
经过一番研究,我发现来自 Apache (http://hc.apache.org/) 的 HttpComponents 库包含了几乎所有您需要以非常简单的方式构建 HTTP-POST 请求的所有内容。
这是一种将带有文件的 POST 请求发送到特定 URL 的方法:
public static void upload(URL url, File file) throws IOException, URISyntaxException {
HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send
FileBody fileB = new FileBody(file);
MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
request.addPart("file", fileB);
httpPost.setEntity(request);
HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server
if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
System.out.println("Upload successful !");
}
}
为了完成上传,您必须有一个处理该 POST 请求的 php 代码,
在这里:
<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
//Do what you want, SQL insert, logs, etc
}
}
?>
为 Java 方法提供的 URL 对象必须指向 php 代码,例如 http://mysite.com/upload.php,并且可以非常简单地从字符串构建。该文件也可以从表示其路径的字符串构建。
我没有花时间对其进行正确测试,但它是建立在正确的工作解决方案之上的,所以我希望这会对您有所帮助。