HttpClient post多文件上傳

public void post() throws ClientProtocolException, IOException{
        //建立client
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //建立post請求
            HttpPost httppost = new HttpPost(url);
            //文件
            FileBody file1 = new FileBody(new File("F:/download/bc09df07e24c253cc6de4605a9eea07b.jpg"));
            FileBody file2 = new FileBody(new File("F:/download/3feededd6b766d14267eef4c429943c1.jpg"));
            //參數 
            //
            StringBody lng = new StringBody("33.33", ContentType.TEXT_PLAIN);  
            StringBody lat = new StringBody("44.33", ContentType.TEXT_PLAIN); 
            //組建訪問實體
            //如 spring-mvc @RequestParam("lng")Double lng
            //             @RequestParam("lat")Double lat
            //             @RequestParam("file")MultipartFile[] files
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("file", file1)
                    .addPart("file", file2)
                    .addPart("lng", lng)
                    .addPart("lat", lat)
                    .build();
            //設置實體
            httppost.setEntity(reqEntity);
            //設置頭信息
            httppost.setHeader("module", "love");
            httppost.setHeader("code", "111111");
             
            System.out.println("executing request " + httppost.getRequestLine());
            //執行post請求
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                //狀態
                System.out.println(response.getStatusLine());
                //響應實體
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println(EntityUtils.toString(resEntity));
                }
                //關閉HttpEntity流
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
相關文章
相關標籤/搜索