项目中 一些接口 需要暴露出来 以方便其他企业二次开发调用 比如 文件上传等 如果是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 使用