利用 HttpClient 上傳文件

jopen 9年前發布 | 6K 次閱讀 Java HttpClient

 最近的工作需要把從網絡上抓取的圖片批量上傳到服務器,文件上傳用的是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();  
            }  
        }  

    }  

HttpClient的更多用法可參考官方文檔:https://hc.apache.org/httpcomponents-client-4.3.x/examples.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!