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

huangapple go评论82阅读模式
英文:

Setting the Content-Type to application/json in a Java Azure Function

问题

以下是您要翻译的内容:

I have developed a Java Azure function that is triggered by an HTTP Request, performs a query to CosmosDB, and return the retrieved data to the caller (front end). The problem is that the Content-Type of the Azure Function is plain text instead of application/json.

this is the code of my azure function:

@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();   
}

this is my local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "java"
  }
}

this is my host.json

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  } 
}

in particular when I call it using Postman this is what I get
postman call

I tried the following line of code but it didn't work
String json = new Gson().toJson(orders);

I also tried the following but it didn't work
request.getHeaders().put("content-type", "application/json");

thanks a lot in advance for your appreciated help 将 Content-Type 设置为 application/json 在 Java Azure Function 中

英文:

I have developed a Java Azure function that is triggered by an HTTP Request, performs a query to CosmosDB, and return the retrieved data to the caller (front end). The problem is that the Content-Type of the Azure Function is plain text instead of application/json.

this is the code of my azure function:

@FunctionName(&quot;backorders&quot;)
public HttpResponseMessage run(
@HttpTrigger(
name = &quot;req&quot;,
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage&lt;Optional&lt;String&gt;&gt; request,
final ExecutionContext context) {
context.getLogger().info(&quot;Java HTTP trigger processed a request.&quot;);
try{     
createConnection();
} catch (Exception e){
System.out.println(&quot;An error occured when connecting to the DB&quot;);
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body(&quot;An error occured when connecting to the DB&quot;).build();
}
ArrayList&lt;String&gt; supplyPlannerIds = new ArrayList&lt;&gt;();
try{
Map&lt;String,String&gt; headers = request.getQueryParameters();
System.out.println(headers.values());
String param = headers.getOrDefault(&quot;spids&quot;, &quot;&quot;);
if(param.equals(&quot;&quot;)){
System.out.println(&quot;The list of Supply Planner IDs can not be empty&quot;);
return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body(&quot;The list of Supply Planner IDs can not be empty&quot;).build();
} else {
System.out.println(&quot;Parsing the request body&quot;);
supplyPlannerIds = new ArrayList&lt;String&gt;(Arrays.asList(param.split(&quot;,&quot;)));
}
} catch (Exception e){
System.out.println(&quot;An error occured when fetching the SupplyPlannerIds&quot;);
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body(&quot;An error occured when retrieving the list of SupplyPlannerIds from the request&quot;).build();
}
BackorderListRepo orderRepo = new BackorderListRepo(container, supplyPlannerIds);
ArrayList&lt;Backorder&gt; orders = orderRepo.retrieveBackorders();
//String json = new Gson().toJson(orders);
return request.createResponseBuilder(HttpStatus.OK).body(orders).build();   
}

this is my local.settings.json:

{
&quot;IsEncrypted&quot;: false,
&quot;Values&quot;: {
&quot;AzureWebJobsStorage&quot;: &quot;&quot;,
&quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;java&quot;
}
}

this is my host.json

{
&quot;version&quot;: &quot;2.0&quot;,
&quot;extensionBundle&quot;: {
&quot;id&quot;: &quot;Microsoft.Azure.Functions.ExtensionBundle&quot;,
&quot;version&quot;: &quot;[3.*, 4.0.0)&quot;
} 
}

in particular when I call it using Postman this is what I get
postman call

I tried the following line of code but it didn't work
String json = new Gson().toJson(orders);

I also tried the following but it didn't work
request.getHeaders().put(&quot;content-type&quot;, &quot;application/json&quot;);

thanks a lot in advance for your appreciated help 将 Content-Type 设置为 application/json 在 Java Azure Function 中

答案1

得分: 0

你差不多到了那个地方:在HTTP中,有分开的请求和响应头,你尝试添加一个请求头而不是响应头。

在你的最后一句中尝试这个:

return request.createResponseBuilder(HttpStatus.OK).header(&quot;Content-Type&quot;, &quot;application/json&quot;).body(orders).build();
英文:

You were nearly there: in HTTP there are separated headers for request and response, and you tried to add a request header instead of a response header.

Try this in your last statement:

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

huangapple
  • 本文由 发表于 2023年6月14日 23:22:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定