public static void sendPost(String msg) throws ClientProtocolException, IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
String requestJson = "{\"text\": \"" + msg + "\"}";
StringEntity stringEntity = new StringEntity(requestJson, "UTF-8");
HttpPost httpPost = new HttpPost(POST_URL);
httpPost.addHeader("Content-type", "application/json");
httpPost.setEntity(stringEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity responseEntity = response.getEntity();
return responseEntity != null ? EntityUtils.toString(responseEntity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
Comments