提问人:Fra_Di_Rienzo 提问时间:6/14/2023 最后编辑:Fra_Di_Rienzo 更新时间:6/14/2023 访问量:251
在 Java Azure 函数中将 Content-Type 设置为 application/json
Setting the Content-Type to application/json in a Java Azure Function
问:
我开发了一个由 HTTP 请求触发的 Java Azure 函数,该函数对 CosmosDB 执行查询,并将检索到的数据返回给调用方(前端)。问题在于 Azure 函数的 Content-Type 是纯文本,而不是 application/json。
这是我的 Azure 函数的代码:
@FunctionName("backorders")
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
try{
createConnection();
} catch (Exception e){
System.out.println("An error occured when connecting to the DB");
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occured when connecting to the DB").build();
}
ArrayList<String> supplyPlannerIds = new ArrayList<>();
try{
Map<String,String> headers = request.getQueryParameters();
System.out.println(headers.values());
String param = headers.getOrDefault("spids", "");
if(param.equals("")){
System.out.println("The list of Supply Planner IDs can not be empty");
return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("The list of Supply Planner IDs can not be empty").build();
} else {
System.out.println("Parsing the request body");
supplyPlannerIds = new ArrayList<String>(Arrays.asList(param.split(",")));
}
} catch (Exception e){
System.out.println("An error occured when fetching the SupplyPlannerIds");
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occured when retrieving the list of SupplyPlannerIds from the request").build();
}
BackorderListRepo orderRepo = new BackorderListRepo(container, supplyPlannerIds);
ArrayList<Backorder> orders = orderRepo.retrieveBackorders();
//String json = new Gson().toJson(orders);
return request.createResponseBuilder(HttpStatus.OK).body(orders).build();
}
这是我local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "java"
}
}
这是我host.json
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.*, 4.0.0)"
}
}
特别是当我使用 Postman 调用它时,这就是我得到的 postman 调用
我尝试了以下代码行,但没有用String json = new Gson().toJson(orders);
我也尝试了以下方法,但没有用request.getHeaders().put("content-type", "application/json");
提前非常感谢您的帮助:)
答:
0赞
cyberbrain
6/14/2023
#1
你快到了:在HTTP中,请求和响应有单独的标头,你试图添加请求标头而不是响应标头。
在上一句话中试试这个:
return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(orders).build();
评论