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

标签 java angular http-post azure-functions

我将 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!' );
        })
      )
  }
}

当项目接收到 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 内容处置:表单数据; ....

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

最佳答案

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

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

    }
  • 测试。我和 postman 一起测试 enter image description here enter image description here
  • 关于java - 如何从azure函数java中的POST请求中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875665/

    相关文章:

    node.js - angular2 2.0.0 未满足的对等依赖关系 rxjs@5.0.0-beta.12,npm WARN angular2-jwt@0.1.22 需要 rxjs@5.0.0-beta.11 的对等体

    html - 如何在父 [Angular] 中两次调用的子组件上动态应用 CSS

    angular - 错误 : 422 (Unprocessable Entity). Angular4

    HTTP GET 和 POST 语义和限制

    java - ExpandableListView 中奇怪的空指针异常

    java - 在java中按顺序创建唯一的订单号?

    java - 如何使用 SQLJ 在 Oracle SQL Developer 控制台上进行打印

    javascript - 从子组件到父组件的输出无法正常工作

    Ruby Mechanize 不通过请求传递 cookie

    java - 为 JTable 中的列中的特定单元格着色