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

如何在Java Azure Function中设置Content-Type为application/json

解决方案:修复Java Azure Function返回Content-Type为application/json

要解决返回Content-Type为plain text的问题,核心是在响应中显式设置Content-Type头,同时确保返回内容为正确的JSON格式。以下是具体实现方案:

方法1:使用Gson序列化并配置响应头

你之前尝试过用Gson转换对象,但缺少关键的响应头设置。修改代码如下:

// 确保已导入Gson类
import com.google.gson.Gson;

// ... 原有业务代码 ...

BackorderListRepo orderRepo = new BackorderListRepo(container, supplyPlannerIds);
ArrayList<Backorder> orders = orderRepo.retrieveBackorders();

// 将对象序列化为标准JSON字符串
String json = new Gson().toJson(orders);

// 构建响应时显式指定Content-Type为application/json
return request.createResponseBuilder(HttpStatus.OK)
        .header("Content-Type", "application/json")
        .body(json)
        .build();

补充:添加Gson依赖

如果是Maven项目,需在pom.xml中引入依赖:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- 使用最新稳定版本即可 -->
</dependency>

方法2:直接返回对象并设置响应头

若不想手动序列化,也可直接返回ArrayList<Backorder>,但必须显式配置响应头,让Azure Functions正确识别内容类型:

BackorderListRepo orderRepo = new BackorderListRepo(container, supplyPlannerIds);
ArrayList<Backorder> orders = orderRepo.retrieveBackorders();

return request.createResponseBuilder(HttpStatus.OK)
        .header("Content-Type", "application/json")
        .body(orders)
        .build();

原尝试失败原因说明

  • 修改request.getHeaders()无效:你操作的是请求头,而非返回给客户端的响应头,无法改变Content-Type结果。
  • 仅用Gson转JSON但未设响应头:Azure Functions默认会将字符串识别为plain text,必须手动指定Content-Type为application/json才能正确标识返回格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:05:26