java 模拟浏览器 上传文件 (httpclient)

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);
        }

你可能感兴趣的:(java开发)