我开发了一个Java Azure函数,该函数由HTTP请求触发,对CosmosDB执行查询,并将检索到的数据返回给调用者(前端)。问题是 Azure Function 的 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)"
}
}
我尝试了以下代码行,但它不起作用
String json = new Gson().toJson(orders);
我也尝试了以下方法,但没有成功
request.getHeaders().put("content-type", "application/json");
提前非常感谢您的帮助:)
您就快到了:在 HTTP 中,请求和响应有单独的标头,并且您尝试添加请求标头而不是响应标头。
在你的最后一个陈述中尝试这个:
return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(orders).build();