我正在尝试使用Apache HTTPComponents Client 4.5.9中的CloseableHttpClient
通过HTTP请求将文件上传到服务器上的PHP脚本。
在运行程序时,出现以下错误:
Jul 15, 2019 8:26:39 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {}->http://homelegacytech.com:80: Software caused connection abort: socket write error
Jul 15, 2019 8:26:39 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->http://homelegacytech.com:80
这是我的Java代码:
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build())
{
HttpPost httpPost = new HttpPost("http://homelegacytech.com/uploads.php");
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("user", user.getUserName()));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8.name()));
File file = new File(this.zipFileURL);
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
ContentType contentType = ContentType.MULTIPART_FORM_DATA;
MyFileBody cbFile = new MyFileBody(file, contentType);
mpEntity.addPart("zip_file", cbFile);
httpPost.setEntity(mpEntity.build());
System.out.println("Sending request to: " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if(resEntity != null)
System.out.println("Response: " + EntityUtils.toString(resEntity));
if(resEntity != null)
EntityUtils.consume(resEntity);
}
这是我在服务器上的PHP代码:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['zip_file']['name'];
$file_size =$_FILES['zip_file']['size'];
$file_tmp =$_FILES['zip_file']['tmp_name'];
$file_type=$_FILES['zip_file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['zip_file']['name'])));
if($file_ext !== 'zip'){
$errors[]="extension not allowed, please choose a zip file.";
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
请问可能是问题所在,因为文件未上传? 该文件大约只有5MB,是一个zip文件。