HttpClient用POST上传文件

文件上传用的是Apache HttpClient 4.3。

/** * Example how to use multipart/form encoded POST request. */ 
public class ClientMultipartFormPost { 

    public static void main(String[] args) throws Exception { 
        if (args.length != 1)  { 
            System.out.println("File path not given"); 
            System.exit(1); 
        } 
        CloseableHttpClient httpclient = HttpClients.createDefault(); 
        try { 
            HttpPost httppost = new HttpPost("http://localhost:8080" + 
                    "/servlets-examples/servlet/RequestInfoExample"); 

            FileBody img = new FileBody(new File(args[0])); 
            StringBody filename = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); 
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); 

            HttpEntity reqEntity = MultipartEntityBuilder.create() 
                    .addPart("img", img) 
                    .addPart("filename", filename) 
                    .addPart("comment", comment) 
                    .build(); 


            httppost.setEntity(reqEntity); 

            System.out.println("executing request " + httppost.getRequestLine()); 
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try { 
                System.out.println("----------------------------------------"); 
                System.out.println(response.getStatusLine()); 
                HttpEntity resEntity = response.getEntity(); 
                if (resEntity != null) { 
                    System.out.println("Response content length: " + resEntity.getContentLength()); 
                } 
                EntityUtils.consume(resEntity); 
            } finally { 
                response.close(); 
            } 
        } finally { 
            httpclient.close(); 
        } 
    } 

}

转自:http://www.open-open.com/lib/view/open1410704032180.html

有谁玩海岛奇兵的,可以加我战队:壹號 。

你可能感兴趣的:(httpclient,上传文件)