JAvaシミュレーションブラウザアップロードファイル(httpclient)

3175 ワード

public static String httpClientUploadFile(String url, File file,Map params) {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                String result = "";
                //  post       。    ,               。
                String boundary ="--------------20200103121104567";
                try {
                        HttpPost httpPost = new HttpPost(url);
                        //     
                        httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);

                        //HttpEntity builder
                        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                        //    
                        builder.setCharset(Charset.forName("UTF-8"));
                        //     
                        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                        //boundary
                        builder.setBoundary(boundary);
                        //multipart/form-data
                        builder.addPart("file",new FileBody(file));//   
                        // binary
//            builder.addBinaryBody("name=\"file\"; filename=\"test.txt\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, file.getName());//    
                        //    
                        for (Map.Entry entry : params.entrySet()) {
                            builder.addTextBody(entry.getKey(), entry.getValue(), contentType );
                        }
                        //HttpEntity
                        HttpEntity entity = builder.build();
                        httpPost.setEntity(entity);
                        //     
                        HttpResponse response = httpClient.execute(httpPost);
                        //  
                        HttpEntity responseEntity = response.getEntity();
                        if (responseEntity != null) {
                                //            
                                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {
                        try {
                                httpClient.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
                System.err.println("result"+result);
                return result;
        }

        //main   
        public static void main(String[] args) {
            Map params = new HashMap<>();
		    params.put("name","  ");
		    params.put("otherParam","123456");
            httpClientUploadFile("http://127.0.0.1:8080/upload",new File("d:/temp/test.txt"),params);
        }