Java - Sending Message to Slack Webhook - java

I'm trying to send a message using Slack incoming webhooks. I have the following code. It runs, but when I check my slack, there is no message. Can anyone see what I may have done wrong.
public class SlackTest {
static String web_hook_url = "https://hooks.slack.com/services/***********/******************";
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(web_hook_url);
try {
String json = "{\"name\": John}";
System.out.println(json);
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
client.execute(httpPost);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

I first used Postman to test sending the message. Then used Postman to generate the corresponding Java code. Then adjusted the code a bit to arrive at the following . . .
OkHttpClient client2 = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{ \"text\" : \"more text"\" }");
Request request2 = new Request.Builder()
.url("https://hooks.slack.com/services/********/*********/***************")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Host", "hooks.slack.com")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();
Response response2 = client2.newCall(request2).execute();

This has been working for me today
public void sendByWebHook(String msg) throws SlackApiException {
assert slackMessage != null : "null slackMessage";
final String METHOD_NAME = "sendByWebHook";
final String HOOK_URL = "https://hooks.slack.com/services/T.../B.../FooBar...";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(HOOK_URL);
try {
String json = "{ \"text\" : \"" + msg + ""\" }";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
client.execute(httpPost);
client.close();
} catch (UnsupportedEncodingException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
} catch (ClientProtocolException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
} catch (IOException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
}
}

Related

connection time out in godaddy server

if face problem just in Godaddy server when executing google API the request return connection time out,
only this request.
but on my other servers (digital ocean and local server), it runs and everything is well and same code and the same configuration
String dataSTR = data.toString();
HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
StringEntity params = new StringEntity(dataSTR, "UTF-8");
String key = "key=" + authKey;
request.addHeader("Authorization", key);
request.addHeader("content-type", "application/json");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("content-type", "charset=UTF-8");
request.setEntity(params);
System.out.println(request);
System.out.println("______");
HttpResponse response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
System.out.println(response);
} catch (ClientProtocolException e) {
LOGGER.error(e.getMessage(), e);
return false;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
}

cannot resolve method create 'com.google.common.net.MediaType,java.lang.String)

I want to send a device to device Firebase notification using OkHttp 3, but am getting the following error when posting the JSON:
cannot resolve method create 'com.google.common.net.MediaType,java.lang.String)
Here is my code:
final String legacyServerKey = "";
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", "Hi this is sent from device to device");
dataJson.put("title", "dummy title");
json.put("notification", dataJson);
json.put("to", reg_token);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=" + legacyServerKey)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
It looks like you imported com.google.common.net.MediaType. You need okhttp3.MediaType

Unable to post JSON data using HttpPost

I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"

Can't translate Postman request to Java

I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.

App crashes on httGet when attempting to send to Json?

My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;

Categories

Resources