如何从 Azure 函数 java 中的 POST 请求中提取数据

How to extract data from POST request in azure functions java

我将来自 angular 应用程序的 POST 请求中的表单数据发送到我在 java.
中编写的 azure 函数 客户端看起来像这样:

  @Injectable({
    providedIn: 'root'
  })
  export class SendItemToAzureFunctionsService {

  private functionURI: string;

  constructor(private http: HttpClient) {
    this.functionURI  =  'https://newsfunctions.azurewebsites.net/api/HttpTrigger-Java?code=k6e/VlXltNs7CmJBu7lmBbzaY4tlo21lXaLuvfG/tI7m/XXXX';
  }

  // {responseType: 'text'}
  sendItem(item: Item){
    let body = new FormData();
    body.append('title', item.title);
    body.append('description', item.description);
    body.append('link', item.link);

    return this.http.post(this.functionURI, body)
      .pipe(
        map((data: string) => {
          return data;
        }), catchError( error => {
          return throwError( 'Something went wrong!' );
        })
      )
  }
}

当项目接收到 azure 函数时。
功能的目的是通过 firebase 在推送通知中将此项目发送到 android 应用程序。

带 HTTP 触发器的 azure 函数如下所示:

@FunctionName("HttpTrigger-Java")
public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.GET,
        HttpMethod.POST }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a request.");

    // Parse query parameter
    String itemDetails = request.getBody().get();

    if (itemDetails == null) {
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                .body("Please pass a name on the query string or in the request body").build();
    } else {
        // ======
        String postUrl = "https://fcm.googleapis.com/fcm/send";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(postUrl);
        post.setHeader("authorization", FIREBAE_AUTH);
        post.setHeader("Content-type", "application/json");
        JSONObject contentJson = new JSONObject();
        contentJson.put("title", "example title");
        contentJson.put("description", "example text");
        JSONObject pushNotificationJson = new JSONObject();
        pushNotificationJson.put("data", contentJson);
        pushNotificationJson.put("to", "/topics/newsUpdateTopic");
        try {
            StringEntity stringEntity = new StringEntity(pushNotificationJson.toString(), "UTF-8");
            post.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(post);
            System.out.println(response.getEntity().getContent().toString());
        } catch (IOException var9) {
            var9.printStackTrace();
        }
        // =========
    }
    return request.createResponseBuilder(HttpStatus.OK)
            .body("succeed to send new item in push notification to clients").build();
}

当我 运行 String itemDetails = request.getBody().get(); 我得到:

------WebKitFormBoundary2gNlxQx5pqyAeDL3 Content-Disposition:表单数据; ....

我很高兴知道如何从中获取数据项?

如果想用java解析Azure函数中from-date类型的数据,可以尝试使用SDKorg.apache.commons.fileupload中的MultipartStream来实现。例如

  1. 代码
public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) throws IOException {
        context.getLogger().info("Java HTTP trigger processed a request.");


        String contentType = request.getHeaders().get("content-type");
        String body = request.getBody().get(); // Get request body
        String boundary = contentType.split(";")[1].split("=")[1]; // Get boundary from content-type header
        int bufSize = 1024;
        InputStream in = new ByteArrayInputStream(body.getBytes()); // Convert body to an input stream
        MultipartStream multipartStream  = new MultipartStream(in, boundary.getBytes(), bufSize, null); // Using MultipartStream to parse body input stream
        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            String header = multipartStream.readHeaders();
            int start =header.indexOf("name=") + "name=".length()+1;
            int end = header.indexOf("\r\n")-1;
            String name = header.substring(start, end);
            System.out.println(name);
            multipartStream.readBodyData(System.out);
            System.out.println("");
            nextPart = multipartStream.readBoundary();
        }
        return request.createResponseBuilder(HttpStatus.OK).body("success").build();

    }
  1. 测试。我和邮递员一起测试

我使用了@Jim Xu 的代码并创建了一个 class 来以更简单的方式获取数据。这是要点 - https://gist.github.com/musa-pro/dcef0bc23e48227e4b89f6e2095f7c1e