在使用JAVA的azure函数中,如何获取请求体

时间:2018-06-13 11:48:01

标签: azure azure-functions

在使用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&gt;,当我在控制台上打印正文时,就像我在上面粘贴的代码一样,我在控制台中获取它。

**********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>

1 个答案:

答案 0 :(得分:3)

我想你可以做到

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

请参阅this article上的完整示例。