接口测试 文件上传 HttpClient Fluent MultipartEntityBuilder​​​​​​​

项目中 一些接口 需要暴露出来 以方便其他企业二次开发调用 比如 文件上传等 如果是Base64码 传的话 文件足够大 那这个base64的字符串会特别长 遂决定用这种 httpClient Fluent 模拟表单提交

Fluent提供了很轻量级的Http请求方法,Fluent API只暴露了一些最基本的HttpClient功能。这样,Fluent API就将开发者从连接管理、资源释放等繁杂的操作中解放出来,从而更易进行一些HttpClient的简单操作。

网上有很多 基本都是类似的写法 我就不多描述了

贴上 自己的代码 仅供参考

 

依赖:

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>fluent-hc</artifactId>
    <version>4.5.2</version>
</dependency>

接下来的代码就厉害了:

public static void main(String[] args) throws IOException {

        // 上传文件 调用接口 测试。
        File file = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹 (2)\\测试.zip");
        //创建表单
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName("utf-8"));
        builder.addTextBody("username", "123");
        builder.addTextBody("password", "123");
        builder.addTextBody("key", "zheshiyigekey");
        builder.addBinaryBody("file", file);
//        builder.addBinaryBody("file", new FileInputStream(file));
//        builder.addBinaryBody("file", IOUtils.readNBytes(new FileInputStream(file), 1024));

        String content = Request.Post("http://127.0.0.1:8010/CorrelatedCertificate/uploadInvoice")
                .body(builder.build())
                .execute().returnContent().asString();

        System.out.println(content);

    }

是不是很简单?没错,我这是精简了很多。

 

参考:

接口测试之文件上传—MultipartEntityBuilder

Apache HttpComponents(HTTPClient) Fluent API 使用

HttpClient4.2 Fluent API学习

MultipartEntitybuilder-API

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值