How to upload a file using Java HttpClient library working with PHP

前端 未结 10 2349
旧巷少年郎
旧巷少年郎 2020-11-22 08:48

I want to write Java application that will upload a file to the Apache server with PHP. The Java code uses Jakarta HttpClient library version 4.0 beta2:

impo         


        
10条回答
  •  感动是毒
    2020-11-22 09:11

    Ok, the Java code I used was wrong, here comes the right Java 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();
      }
    }
    

    note using MultipartEntity.

提交回复
热议问题