收藏
回答

为什么我从服务端发multipart/form-data时一直提示not well-formed?

如下是我组装post请求的代码:

我发现同样是是是用这个方法,当我上传一个.png文件的时候,就没有问题,但是当我上传一个.xlsx文件后,就反复失败,提示:

  • The body of your POST request is not well-formed multipart/form-data.
  • MalformedPOSTRequest

在网上搜了相关资料,把MediaType.parse的内容改成了application/vnd.openxmlformats-officedocument.spreadsheetml.sheet之后也是一样的报错


public static String sendMultipartPost(String url, Map<String, String> body, File file, Map<String, String> headers) throws IOException {
    log.info("request url: {}, body: {}, headers: {}", url, body, headers);
    MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(),
                    RequestBody.create(MediaType.parse("multipart/form-data"), file));
    if (body != null && !body.isEmpty()) {
        body.forEach(multipartBodyBuilder::addFormDataPart);
    }

    MultipartBody multipartBody = multipartBodyBuilder.build();

    Request.Builder builder = new Request.Builder();
    if (headers != null && !headers.isEmpty()) {
        headers.forEach(builder::addHeader);
    }
    Request request = builder
            .url(url)
            .post(multipartBody)
            .build();

    try (Response response = client.newCall(request).execute()) {
        String responseBody = response.body().string();
        log.info("the response body is: {}", responseBody);
        return responseBody;
    }
}
回答关注问题邀请回答
收藏

1 个回答

  • Mr.Zhao
    Mr.Zhao
    09-07

    哪个接口

    09-07
    有用
    回复
登录 后发表内容
问题标签