Home >Java >javaTutorial >Why is my Java HttpClient file upload to PHP failing, despite a successful request and response?
Upload Files with Java HttpClient and PHP
In this scenario, you're attempting to upload a file to Apache with PHP using the Java HttpClient library version 4.0 beta2. However, the is_uploaded_file method returns false and the $_FILES variable remains empty, despite a seemingly successful request and response.
Cause
The original Java code is incorrect. To rectify this issue, utilize the following updated class:
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(); } }
The primary distinction is the utilization of MultipartEntity. The original implementation lacked this essential component, resulting in the PHP script's inability to recognize the uploaded file.
The above is the detailed content of Why is my Java HttpClient file upload to PHP failing, despite a successful request and response?. For more information, please follow other related articles on the PHP Chinese website!