wg2moiLi8K425oUo
wg2moiLi8K425oUo

Reputation: 125

Java: Send POST curl command to send a message in slack

I have a selenium java automation and I need to send the following CURL command in my java code:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Test"}' https://hooks.slack.com/services/XXX/YYY/ZZZ

I tried some solutions I found here like:

String command = "curl -X POST -H 'Content-type: application/json' --data '{"text":"Test"}' https://hooks.slack.com/services/XXX/YYY/ZZZ";
Runtime.getRuntime().exec(command);

And also this one:

HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://hooks.slack.com/services/XXX/YYY/ZZZ");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("text", "test"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = client.execute(post);

The script runs, but nothing happens (no message/warning/error on Eclipse console), it just runs and pass successfully, but the message is not sent on Slack channel. If I run this same curl command in my linux terminal, the message is sent on Slack.

I'm still learning Java, so probably I'm doing something wrong very obviously.

Upvotes: 0

Views: 1021

Answers (1)

wg2moiLi8K425oUo
wg2moiLi8K425oUo

Reputation: 125

I could finally made it to work:

String[] command = new String[] { "/bin/bash", "-c", "curl -X POST -H 'Content-type: application/json' --data '{\"text\":\"test\"}' https://hooks.slack.com/services/AAA/BBB/CCC"};
Process proc = new ProcessBuilder(command).start();

Upvotes: 1

Related Questions