【问题标题】:Should I set the Content-Type header for a MultipartEntity?我应该为 MultipartEntity 设置 Content-Type 标头吗?
【发布时间】:2017-04-20 05:32:37
【问题描述】:

我有一小段代码在同一个 POST 中提交一个 XML 实体和二进制数据。我为此使用了 httpclienthttpmime

我不太确定是否应该为此请求设置Content-Type 标头。毕竟Content-Type 既是application/xml 又是application/octet-stream

这个的正确用法是什么?

    post = new HttpPost(uri);
    post.setHeader("Authorization", auth);

    // Should I set Content-Type at all?
    post.setHeader("Content-Type", mimeType + ";charset=UTF-8");

    MultipartEntityBuilder b = MultipartEntityBuilder.create();
    b.addTextBody("data", payload, ContentType.APPLICATION_XML);
    b.addBinaryBody("file", file);
    post.setEntity(b.build());

【问题讨论】:

    标签: java apache-httpclient-4.x


    【解决方案1】:

    不,你不应该。您应该让 HttpClient 根据消息实体的属性自动生成Content-Type 以及其他内容元数据标头。

    【讨论】:

    • 谢谢!我认为这个答案仅在我们谈论多部分身体时适用?如果主体是一个简单的 StringEntity,我肯定必须声明它是 XML、JSON 还是其他。
    • 不,同样的原则同样适用于所有实体。例如,在使用 ContentType 参数创建 StringEntity 时,确实应该指定内容的类型。
    • 所以这意味着我不应该与请求本身的 Content-Type 标头交互 - 而只能通过构造函数设置内容类型,例如字符串实体?不过,这个构造函数不允许我同时设置字符集和内容类型。
    • StringEntity entity = new StringEntity("stuff", ContentType.create("text/plain", StandardCharsets.UTF_8));
    • StringEntity entity = new StringEntity("stuff", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2015-05-05
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多