/
Implementing Cloud Task To Create HTTP Tasks

Implementing Cloud Task To Create HTTP Tasks

Crete a new java class in your project named CloudTaskUtil.java or use any existing util class.

  • Copy the below mentioned code contents in the util class.

  • Add the required dependencies mentioned below in POM.xml file.

  • Create a new task queue or use an existing one, and pass task queue name as queueId in the createTask method.

  • The target of this HTTP task is passed in as url in the createTask method, we need to mention the complete URL of the destination endpoint/API.

 

 

Dependencies for Cloud Task

<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.22.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-tasks</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.truth</groupId> <artifactId>truth</artifactId> <version>1.1.5</version> <scope>test</scope> </dependency> </dependencies>



Method to created HTTP tasks

import com.google.cloud.tasks.v2.CloudTasksClient; import com.google.cloud.tasks.v2.HttpMethod; import com.google.cloud.tasks.v2.HttpRequest; import com.google.cloud.tasks.v2.QueueName; import com.google.cloud.tasks.v2.Task; import com.google.protobuf.ByteString; import java.io.IOException; import java.nio.charset.Charset; public class CreateHttpTask {   // Create a task with a HTTP target using the Cloud Tasks client.   public static void createTask(String payload, String queueId, String url)       throws Exception { // Instantiates a client. try (CloudTasksClient client = CloudTasksClient.create()) { String locationId = "asia-south1"; // Construct the fully qualified queue name. // cloudTaskProject is the project ID of the project where service is deployed. String queuePath = QueueName.of(Config.cloudTaskProject, locationId, queueId).toString(); // Construct the task body. Task.Builder taskBuilder = Task.newBuilder() .setHttpRequest( HttpRequest.newBuilder() .setBody(ByteString.copyFrom(payload, Charset.defaultCharset())) .setHttpMethod(HttpMethod.POST) .setUrl(url) .build()); // Send create task request. Task task = client.createTask(queuePath, taskBuilder.build()); System.out.println("Task created: " + task.getName()); } catch(Exception ex){ logger.error("Unable to create task : " + ex.getMessage()); logger.error("Internal server error while publishing time to deliver. Error message : " + ex.getMessage() + " In class : " + ex.getStackTrace()[0].getClassName() + " at line : " + ex.getStackTrace()[0].getLineNumber()); } } }

 

Related content