【安卓】使用企业微信机器人发送消息

package com.example.gpsapp0719;
import android.os.AsyncTask;
import android.util.Log;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeiXinMsg {

private static final String WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_key";

public static void sendMessage(final String message) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
send(message);
return null;
}
}.execute();
}

private static void send(String message) {
try {
URL url = new URL(WEBHOOK_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);

String postData = "{"msgtype":"text","text":{"content":"" + message + ""}}";
OutputStream outputStream = conn.getOutputStream();
outputStream.write(postData.getBytes("UTF-8"));
outputStream.close();

int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("WeChatRobot", "Message sent successfully!");
} else {
Log.e("WeChatRobot", "Failed to send message. Response code: " + responseCode);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
Log.e("WeChatRobot", "Exception occurred: " + e.getMessage());
}
}
}

posted @ 2023-07-20 01:00  Rainflow  阅读(143)  评论(0)    收藏  举报