对接企业微信的java代码案例
时间: 2023-10-05 14:10:16 浏览: 97
以下是一个使用Java代码对接企业微信的示例:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WeChatApi {
private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
private String corpId;
private String secret;
private String agentId;
private String accessTokenUrl;
private String sendMessageUrl;
private OkHttpClient httpClient;
public WeChatApi(String corpId, String secret, String agentId) {
this.corpId = corpId;
this.secret = secret;
this.agentId = agentId;
this.accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + secret;
this.sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
this.httpClient = new OkHttpClient();
}
public String getAccessToken() throws IOException {
Request request = new Request.Builder().url(accessTokenUrl).build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
String responseBody = response.body().string();
JSONObject jsonObject = JSON.parseObject(responseBody);
return jsonObject.getString("access_token");
} else {
throw new IOException("Failed to get access token: " + response.message());
}
}
public void sendMessage(String message) throws IOException {
String accessToken = getAccessToken();
String url = sendMessageUrl + accessToken;
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("touser", "@all");
requestMap.put("msgtype", "text");
Map<String, String> contentMap = new HashMap<>();
contentMap.put("content", message);
requestMap.put("text", contentMap);
requestMap.put("agentid", agentId);
RequestBody requestBody = RequestBody.create(JSON_MEDIA_TYPE, JSON.toJSONString(requestMap));
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Failed to send message: " + response.message());
}
}
}
```
使用示例:
```java
WeChatApi api = new WeChatApi("YOUR_CORP_ID", "YOUR_SECRET", "YOUR_AGENT_ID");
api.sendMessage("Hello, World!");
```
阅读全文