使用WebClient发送byte数组报No suitable writer错误如何解决
问题根因
报错核心是两个配置问题:
- Spring 默认的 Multipart 消息编码器没有适配
ByteArrayInputStream类型的序列化逻辑,找不到对应的 Writer 来序列化该部分请求内容 - 手动拼接的
Content-Disposition头不符合标准规范,表单类型的 Content-Disposition 必须包含name属性,自定义的格式缺失了必填项 - 重复设置了
Content-Type请求头,contentType()方法会自动生成带 boundary 的合法 multipart 头,手动追加的 header 会覆盖边界参数导致请求格式异常
修复方案
优先选择更简单的原生支持方案:直接传入byte数组本身,Spring默认提供了byte数组的专属编码器,不需要额外包装成InputStream。
修正后可运行代码
HttpClient httpClient = HttpClient.create(); // 原有代理配置保持不变 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient); WebClient client = WebClient.builder().clientConnector(connector).build(); MultipartBodyBuilder formDataBuilder = new MultipartBodyBuilder(); // 直接传入byte数组,可根据业务调整part的Content-Type formDataBuilder.part("pack", pack, MediaType.APPLICATION_OCTET_STREAM) // 追加自定义pack属性,不需要覆盖整个Content-Disposition头 .header("Content-Disposition", "form-data; name=\"pack\"; pack=\"你需要传入的pack属性值\""); formDataBuilder.part("simpleParam", "testParam"); Response response = client.post().uri("myurl.test") .accept(MediaType.APPLICATION_XML) .contentType(MediaType.MULTIPART_FORM_DATA) // 移除手动设置的Content-Type header,避免覆盖自动生成的boundary .body(BodyInserters.fromMultipartData(formDataBuilder.build())) .retrieve() .bodyToMono(Response.class) .block();
备选方案(必须使用InputStream场景)
如果业务要求必须用InputStream作为part内容,需要手动注册对应的编码器:
WebClient client = WebClient.builder() .clientConnector(connector) .codecs(configurer -> { // 注册InputStream专属编码器 configurer.customCodecs().register(new InputStreamHttpMessageWriter()); }) .build();
内容的提问来源于stack exchange,提问作者User1254
相关产品推荐
相关产品推荐

