PAYATHON 2026

如何用 Java BodyPublishers 复现 C# MultipartFormDataContent?

数据小陈

结论:不是。 这段 Java 代码没有复现 C# 的 MultipartFormDataContent。C# 那边发的是 multipart/form-data,Java 示例却把 Content-Type 设成了 application/json,还用 BodyPublishers.concat 把几段 JSON 直接拼在一起。这样发出去的内容既不是合法 JSON,也不是 multipart 表单,服务端返回 bad request 并不意外。

原因

  1. Content-Type 对不上:MultipartFormDataContent 对应的是 multipart/form-data; boundary=...。
  2. BodyPublishers.concat 只是按字节把 publisher 接起来,不会合并 JSON 对象,也不会生成 boundary 和 part 头。
  3. ?、& 在 multipart 的 part 内容里就是普通字符,一般不用做 URL 编码;C# 的 MultipartFormDataContent 默认也不是 URL 编码表单。
  4. 如果接口确实要 JSON,应该发一个完整的 JSON 对象,交给 JSON 库序列化,而不是拼多个 JSON 片段。

复现 multipart/form-data

Java 11+ 可以用 HttpRequest.BodyPublishers 手动拼出 multipart body:

import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;

String boundary = "----JavaBoundary" + System.nanoTime();
ByteArrayOutputStream body = new ByteArrayOutputStream();

appendPart(body, boundary, "method", "getValue");
appendPart(body, boundary, "username", username);
appendPart(body, boundary, "password", password);
appendPart(body, boundary, "advanced", "true");
body.writeBytes(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.endpoint"))
    .header("Content-Type", "multipart/form-data; boundary=" + boundary)
    .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()))
    .build();

private static void appendPart(ByteArrayOutputStream out,
                               String boundary,
                               String name,
                               String value) {
    String part = "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=\"" + name + "\"\r\n" +
        "Content-Type: text/plain; charset=utf-8\r\n" +
        "\r\n" +
        value + "\r\n";
    out.writeBytes(part.getBytes(StandardCharsets.UTF_8));
}

请求头里的 boundary 必须和 body 中的完全一致。用户名和密码直接写进 part 就行,?、& 不会破坏 multipart。实际使用时最好换一个更随机的 boundary,并统一用 UTF-8。示例里 Java builder 的括号也要写完整:POST(...) 之后再调用 .build()。

如果抓包确认接口要的是 JSON,就别用 BodyPublishers.concat 拼多个对象。把四个字段放进同一个 JSON 对象,用 Jackson/Gson 之类的库序列化,再把 Content-Type 设成 application/json。

备注:内容仅供参考。