【问题标题】:How to extract data from POST request in azure functions java如何在 azure 函数 java 中从 POST 请求中提取数据
【发布时间】:2020-03-26 20:33:09
【问题描述】:

我将 POST 请求中的表单数据从 Angular 应用程序发送到我用 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!' );
        })
      )
  }
}

当项目接收到天蓝色功能时。
函数的目的是通过 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 内容处置:表单数据; ....

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

【问题讨论】:

    标签: java angular http-post azure-functions


    【解决方案1】:

    如果想用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. 测试。我用邮递员测试

    【讨论】:

    • 非常感谢。我还有一个问题。哪一行给出关键值?我发现那一行 System.out.println(name); pring 键名,如标题,但我们如何获取此键的值?在哪一行?我想从中创建 obj。
    • @YaffaHarari 根据您的需要,请将代码multipartStream.readBodyData(System.out); 更新为ByteArrayOutputStream output = new ByteArrayOutputStream(); multipartStream.readBodyData(output); String value=output.toString("UTF-8");
    • 这是工作。我非常感谢。你节省了我的时间。谢谢!
    【解决方案2】:

    我使用了@Jim Xu 的代码并创建了一个类来更轻松地获取数据。这是要点 - https://gist.github.com/musa-pro/dcef0bc23e48227e4b89f6e2095f7c1e

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      相关资源
      最近更新 更多