首页 > 解决方案 > 在使用 JAVA 的 azure 函数中,如何获取请求正文

问题描述

在使用 JAVA 的 azure 函数中,如何获取以 json 形式发送的请求有效负载

我的代码是这样的:

@FunctionName("hello")
    public HttpResponseMessage<String> hello(
            @HttpTrigger(name = "req", methods = {"post"}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,final ExecutionContext context) throws Exception {
        context.getLogger().info("Java HTTP trigger processed a request.");
        System.out.println("**********REQUEST BODY*************"+request.getBody());

        String cookie = new Authenticate().authenticateAndGetCookie();
        ExecuteCommands commandsExecutor = new ExecuteCommands(cookie);
        String s=commandsExecutor.control(request.toString());
        System.out.println(s);

        JSONObject jobj=new JSONObject(s);


        if (s == null) {
            return request.createResponse(400, "Please pass a name on the query string or in the request body");
        } else {
            return request.createResponse(200,jobj.toString());
        }
    }

由于使用了 HttpRequestMessage>,当我在控制台上打印正文时,就像我在上面粘贴的代码中一样,我在控制台中获取它。

**********REQUEST BODY*************Optional[{
[13-06-2018 11:40:18] Java HTTP trigger processed a request.
[13-06-2018 11:40:18]   "Command": "com",
[13-06-2018 11:40:18]   "Id": "id",
[13-06-2018 11:40:18]   "Id2": "id2",
[13-06-2018 11:40:18]   "Operation": "op"
[13-06-2018 11:40:18] }]

但我通过了以下有效载荷:

{
    "Command": "com",
     "Id": "id",
    "Id2": "id2",
    "Operation": "op"
     }

所以,我尝试使用 HttpRequestMessage 但我得到了以下异常

incompatible types: com.microsoft.azure.serverless.functions.HttpRequestMessage<java.util.Optional<java.lang.String>> cannot be converted to com.microsoft.azure.serverless.functions.HttpRequestMessage<java.lang.String>

标签: azureazure-functions

解决方案


我想你可以这样做

String body = request.getBody().orElse("");

请参阅本文中的完整示例。


推荐阅读