Skip to content
Advertisement

How to extract data from POST request in azure functions java

I send form data in POST request from angular app to my azure functions who wrriten in java.
the client side look like this:

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

when Item recived to azure functions.
the aim of functions is to send this item in push notifications via firebase to android app.

the azure functions with HTTP trigger look like this:

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

when I am running String itemDetails = request.getBody().get(); I am getting:

——WebKitFormBoundary2gNlxQx5pqyAeDL3 Content-Disposition: form-data; ….

I will be glad to know how to get data item from that?

Advertisement

Answer

If you want to parse from-date type data in Azure function with java, you can try to use MultipartStream in SDK org.apache.commons.fileupload to implement it. For example

  1. code
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("rn")-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. Test. I test with postman enter image description here enter image description here
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement