Gringo Golf
Gringo Golf

Reputation: 473

Slack incoming web hook and getting it to work with HTTPPOST

Team, I need help with posting a simple Json request to Slack. I setup the configuration and have the URL to use. They want me to add payload={"Text":"Some String"}

I'm using the following code:

HttpPost httppost = new HttpPost("slackURL");
 httppost.addHeader("Content-type", "application/json");
StringEntity params = new StringEntity("payload={\"text\" : \""+message+"\"}","UTF-8");

           params.setContentType("application/json");
            httppost.setEntity(params);

ERROR Message:

HTTP/1.1 500 Server Error
Response content length: -1
Chunked?: true

Response from Slack:

Our logs indicate that the content isn't being posted to the payload HTTP POST/form parameter.

Upvotes: 0

Views: 2698

Answers (1)

user94559
user94559

Reputation: 60133

Change

StringEntity params = new StringEntity("payload={\"text\" : \""+message+"\"}","UTF-8");

to

StringEntity params = new StringEntity("{\"text\" : \""+message+"\"}","UTF-8");

(Get rid of the "payload=", since that's not valid JSON.)

Per the documentation, you have two choices when POSTing to an incoming webhook URL:

  1. You can send the data as JSON in the body of the request.
  2. You can send a payload form-encoded parameter with a JSON value.

You were doing something in between... you were claiming to be sending a JSON-encoded body (via Content-Type: application/json) but you weren't sending valid JSON. (You were sending something that looked more like the form-encoded option, though you weren't actually form-encoding it.)

As a side note: I'd strongly encourage you to use a real library to construct your JSON. Doing it by hand is error prone. E.g., if you tried to encode the message A wise man once said "You shouldn't try to encode JSON by hand.", you'd get an error because of the invalid JSON you generated.

Upvotes: 1

Related Questions