You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI Generator Java:配置multipart请求部件的Content-Type

问题:OpenAPI Generator + RestTemplate生成的Multipart请求中,documentIds字段Content-Type无法设置为application/json

我用Java OpenAPI Generator结合RestTemplate生成客户端,实现通过multipart请求同时上传文件和元数据documentIds。对应的API规范如下:

path:
  /files:
    post:
      ...
      requestBody:
        content:
          multipart/form-data:
            encoding:
              file:
                contentType: multipart/form-data
                style: form
              documentIds:
                contentType: application/json
                style: form
            schema:
              $ref: '#/components/schemas/UploadFileRequest'
...
components:
  schemas:
    UploadFileRequest:
      type: object
      properties:
        documentIds:
          type: array
          items:
            type: string
        file:
          type: string
          format: binary

生成的客户端方法为:

public void postFile(List<String> documentIds, Resource file) {...}

当前遇到的问题:documentIds的Content-Type被自动设置为text/plain,无法被服务端接受。我已尝试在API规范中通过encoding及x-content-type扩展定义该字段的Content-Type,但生成的客户端无任何变化。想咨询是遗漏了配置项,还是该库暂不支持此特性?


原因与解决方案

目前OpenAPI Generator的RestTemplate模板确实存在对multipart请求中复杂类型字段的Content-Type设置支持不足的问题,尤其是数组、对象这类需要JSON序列化的字段,默认只会按text/plain处理。你可以通过以下方式解决:

  • 自定义RestTemplate请求拦截器
    在客户端配置中添加拦截器,手动修改documentIds字段的Content-Type:

    restTemplate.getInterceptors().add((request, body, execution) -> {
        if (request.getHeaders().getContentType() != null 
            && request.getHeaders().getContentType().isCompatibleWith(MediaType.MULTIPART_FORM_DATA)) {
            if (body instanceof MultiValueMap) {
                MultiValueMap<String, Object> multiMap = (MultiValueMap<String, Object>) body;
                if (multiMap.containsKey("documentIds")) {
                    Object ids = multiMap.getFirst("documentIds");
                    try {
                        String jsonIds = new ObjectMapper().writeValueAsString(ids);
                        HttpHeaders headers = new HttpHeaders();
                        headers.setContentType(MediaType.APPLICATION_JSON);
                        multiMap.set("documentIds", new HttpEntity<>(jsonIds, headers));
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException("Failed to serialize documentIds", e);
                    }
                }
            }
        }
        return execution.execute(request, body);
    });
    
  • 修改OpenAPI Generator模板文件
    找到RestTemplate对应的模板(如restTemplate.mustache),在构建multipart请求的逻辑中添加判断:如果字段是集合或对象类型,就将其序列化为JSON并设置application/json的Content-Type,替代默认的text/plain。

  • 检查并升级OpenAPI Generator版本
    部分旧版本存在该特性支持缺陷,升级到最新稳定版后可能自动修复此问题。

内容的提问来源于stack exchange,提问作者Sirea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:45:19