Reputation: 463
I'm using the package google.cloud.tasks.v2
to enqueue a task in a Google App Engine Task Queue. The documentation states:
If the task has a body, Cloud Tasks sets the following headers:
Content-Type
: By default, theContent-Type
header is set to"application/octet-stream"
. The default can be overridden by explicitly settingContent-Type
to a particular media type when the task is created. For example,Content-Type
can be set to"application/json"
.
The text "when the task is created" links here, which does not go into detail about how to change the Content-Type from the default of "application/octet-stream"
. Much Google searching always leads back to the above link.
The task has an HttpRequest
property, which has a Headers
property, but it is read only.
Here's my code so far:
CloudTasksClient cloudTasksClient = CloudTasksClient.Create();
var task = cloudTasksClient.CreateTask(new CreateTaskRequest
{
Parent = parent.ToString(),
Task = new Task
{
HttpRequest = new HttpRequest
{
HttpMethod = HttpMethod.Post,
Url = url,
Body = ByteString.CopyFromUtf8(JsonConvert.SerializeObject(searchToDo)),
},
//ScheduleTime = Timestamp.FromDateTime(
// DateTime.UtcNow.AddSeconds(inSeconds))
}
});
How can I set the Content-Type
to "application/json"
for the HttpRequest
?
Upvotes: 1
Views: 1757
Reputation: 1
The .putHeaders()
builder method can be used to set the headers for the HTTP tasks:
HttpRequest request = HttpRequest.newBuilder()
.setUrl(url)
.setHttpMethod(HttpMethod.GET)
.putHeaders("key", "value")
.build();
Upvotes: 0
Reputation: 16711
As you mentioned in your question, the Google.Cloud.Tasks.V2.HttpRequest
has a readonly Headers
property which is MapField
. While the property is readonly, MapField
does have an Add()
method, which you can use to add the header you need.
Create the HttpRequest
and add the header before creating the Task
:
CloudTasksClient cloudTasksClient = CloudTasksClient.Create();
// create HttpRequest
HttpRequest httpReq = new HttpRequest
{
HttpMethod = Google.Cloud.Tasks.V2.HttpMethod.Post,
Url = url,
Body = ByteString.CopyFromUtf8(JsonConvert.SerializeObject(searchToDo)),
};
// add Content-Type to headers
httpReq.Headers.Add("Content-Type", "application/json");
var task = cloudTasksClient.CreateTask(new CreateTaskRequest
{
Parent = parent.ToString(),
Task = new Task
{
HttpRequest = httpReq, // assign the HttpRequest
...
}
});
Note: I don't use google cloud platform, this is untested and based purely on the docs found online.
Upvotes: 1