Jmeter有个功能是可以上传文件的,上周遇到个问题是不能用Jmeter需要自己实现,所以最终实现的代码如下:
构造发送文件的请求

private MultipartEntity getMutipartEntry(Map<String, Object> param, File file) throws UnsupportedEncodingException {
        if (file == null) {
            throw new IllegalArgumentException("文件不能为空");
        }
        FileBody fileBody = new FileBody(file);
        FormBodyPart filePart = new FormBodyPart("file", fileBody);
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart(filePart);

        Iterator<String> iterator = param.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            FormBodyPart field = new FormBodyPart(key, new StringBody((String) param.get(key)));
            multipartEntity.addPart(field);

        }
        return multipartEntity;
    }

发送上传文件请求

public String postFile(String url,Map<String, Object> param, File file) throws ClientProtocolException, IOException {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(getMutipartEntry(param,file));
        CloseableHttpResponse response = httpClient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            res = EntityUtils.toString(entity, "UTF-8");
            response.close();
        } else {
            res = EntityUtils.toString(entity, "UTF-8");
            response.close();
            throw new IllegalArgumentException(res);
        }
        return res;
    }

还有一种方式

File file =newFile(filePath);
FileBody bin =newFileBody(file); 
StringBody uploadFileName =newStringBody(
          "文书管家.docx", ContentType.create(
          "text/plain", Consts.UTF_8));
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
           .addPart("uploadFile", bin)
           .addPart("uploadFileName", uploadFileName)
           .setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);

发表评论

电子邮件地址不会被公开。 必填项已用*标注