AndroidからSlack WebHookを利用
Android から Slack WebHookにPOSTしてみます。
使用ライブラリ
- Gson
- ButterKnife
- OkHttp
build.gradle の dependencies に追加
compile 'com.jakewharton:butterknife:8.5.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' compile 'com.google.code.gson:gson:2.8.0' compile 'com.squareup.okhttp:okhttp:2.0.0'
コード
送るメッセージを入れるクラス
public class Slack { public String text; public Slack(String text) { this.text = text; } }
ボタンを押したらPOSTする
@OnClick(R.id.button) public void getRequest(final Button button) { button.setEnabled(false); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String result = null; Gson gson = new Gson(); RequestBody requestBody = RequestBody.create( MediaType.parse("text/plain"), gson.toJson(new Slack("Hello")) ); Request request = new Request.Builder() .url("WebHook URL") .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); try { Response response = client.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } // 返す return result; } @Override protected void onPostExecute(String result) { Log.d("result", result); button.setEnabled(true); } }.execute(); }