Create an Amazon SNS subscriber for a message with messageStructure json and a specified messageType

StackOverflow https://stackoverflow.com/questions/21437481

  •  04-10-2022
  •  | 
  •  

Question

I want to subscribe to an Amazon SNS topic; my subscriber is registered with protocol "http".

amazonSNSClient.subscribe(new SubscribeRequest(topicArn, "http", callbackUrl);

When a message is published, the messageStructure is set to "json", and the message content contains entries for "default", "http", and "https".

JSONObject jsonMessage = new JSONObject();
jsonMessage.put(DEFAULT, "foo");
jsonMessage.put(HTTPS, someOtherJsonObject);
jsonMessage.put(HTTP, someOtherJsonObject);

PublishRequest publishRequest = new PublishRequest(topicArn, jsonMessage.toString());
publishRequest.setMessageStructure(MESSAGE_TYPE_JSON);
amazonSNSClient.publish(publishRequest);

The published message is successfully received by Amazon, and a notification is sent to the Subscriber. Verification in the AWS console confirms that my subscriber is subscribed for the "http" protocol. However, the subscriber receives the "default" message instead of the "http"(json) message. What can possibly be wrong, why is Amazon pushing the 'default' notification to the subscriber instead of the 'http' notification?

Was it helpful?

Solution

Can you show us the exact string which is getting sent? My guess is that you are embedding JSON structures inside the message when really you should be just using strings.

For example, I get you are sending something like this:

{
  "default": "foo",
  "http": {"anotherThing":1},
}

When in reality what you need to send is:

{
  "default": "foo",
  "http": "{\"anotherThing\":1}",
}

I would try changing the code to:

JSONObject jsonMessage = new JSONObject();
jsonMessage.put(DEFAULT, "foo");
jsonMessage.put(HTTPS, someOtherJsonObject.toString());
jsonMessage.put(HTTP, someOtherJsonObject.toString());

PublishRequest publishRequest = new PublishRequest(topicArn, jsonMessage.toString());
publishRequest.setMessageStructure(MESSAGE_TYPE_JSON);
amazonSNSClient.publish(publishRequest);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top