|
| 1 | +/* |
| 2 | + * Copyright 2018 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.task; |
| 18 | + |
| 19 | +// [START cloud_tasks_create_http_task] |
| 20 | +import com.google.cloud.tasks.v2beta3.CloudTasksClient; |
| 21 | +import com.google.cloud.tasks.v2beta3.HttpMethod; |
| 22 | +import com.google.cloud.tasks.v2beta3.HttpRequest; |
| 23 | +import com.google.cloud.tasks.v2beta3.QueueName; |
| 24 | +import com.google.cloud.tasks.v2beta3.Task; |
| 25 | +import com.google.protobuf.ByteString; |
| 26 | +import java.nio.charset.Charset; |
| 27 | + |
| 28 | +public class CreateHttpTask { |
| 29 | + |
| 30 | + public static void main(String[] args) throws Exception { |
| 31 | + String projectId = System.getenv("PROJECT_ID"); |
| 32 | + String queueName = System.getenv("QUEUE_ID"); |
| 33 | + String location = System.getenv("LOCATION_ID"); |
| 34 | + String url = System.getenv("URL"); |
| 35 | + |
| 36 | + // Instantiates a client. |
| 37 | + try (CloudTasksClient client = CloudTasksClient.create()) { |
| 38 | + // Variables provided by the system variables. |
| 39 | + // projectId = "my-project-id"; |
| 40 | + // queueName = "my-appengine-queue"; |
| 41 | + // location = "us-central1"; |
| 42 | + // url = "https://<project-id>.appspot.com/tasks/create"; |
| 43 | + String payload = "hello"; |
| 44 | + |
| 45 | + // Construct the fully qualified queue name. |
| 46 | + String queuePath = QueueName.of(projectId, location, queueName).toString(); |
| 47 | + |
| 48 | + // Construct the task body. |
| 49 | + Task.Builder taskBuilder = |
| 50 | + Task.newBuilder() |
| 51 | + .setHttpRequest( |
| 52 | + HttpRequest.newBuilder() |
| 53 | + .setBody(ByteString.copyFrom(payload, Charset.defaultCharset())) |
| 54 | + .setUrl(url) |
| 55 | + .setHttpMethod(HttpMethod.POST) |
| 56 | + .build()); |
| 57 | + |
| 58 | + // Send create task request. |
| 59 | + Task task = client.createTask(queuePath, taskBuilder.build()); |
| 60 | + System.out.println("Task created: " + task.getName()); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | +// [END cloud_tasks_create_http_task] |
0 commit comments