Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send cURL -X POST --data-urlencode with Java

Tags:

java

curl

I've been looking all over the internet for this, and I just haven't found an answer that works. I'm trying to make a bukkit plugin that sends data to an ingoing Slack webhook when a command is run. I've gotten to noticing the command running, but I have no idea how to send the JSON. (For those of you unfamiliar with Slack, the command inside a terminal window is curl -X POST --data-urlencode 'payload={"channel":"#slack-channel-id","username":"bot's username","text":"Self explanatory","icon_emoji":"The bot's icon"}' https://slack.com/custom/webhook/token/here I've been looking all over and googling for a good hour trying to find a way in Java to send this. But no matter what I try it doesn't work. Any help is appreciated, thanks

like image 805
Redrield Avatar asked Mar 13 '23 15:03

Redrield


1 Answers

//You can use the following code it works! slackWebhook is the https endpoint for the channel that you can get from custom_integration link

    String payload = "payload={\"channel\": \"#channel_name\", \"text\": \"This is posted "
            + "to #ewe_gps_abacus_notif and comes from a bot named change-alert.\"}";

    StringEntity entity = new StringEntity(payload,
            ContentType.APPLICATION_FORM_URLENCODED);

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(slackWebhook);
    request.setEntity(entity);

    HttpResponse response = null;
    try {
        response = httpClient.execute(request);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(response.getStatusLine().getStatusCode());
like image 174
ridzi1989 Avatar answered Mar 28 '23 16:03

ridzi1989