java 实现企业微信api工具
时间: 2024-04-19 13:26:15 浏览: 13
Java可以通过使用企业微信提供的API来实现与企业微信的交互。以下是一个简单的Java代码示例,演示如何使用企业微信API发送消息:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class EnterpriseWeChatAPIUtil {
private static final String API_URL = "https://qyapi.weixin.qq.com/cgi-bin/";
public static void main(String[] args) {
// 发送消息示例
String accessToken = getAccessToken();
sendTextMessage(accessToken, "your_corp_id", "your_agent_id", "your_user_id", "Hello, Enterprise WeChat!");
}
// 获取访问令牌
public static String getAccessToken() {
String corpId = "your_corp_id";
String corpSecret = "your_corp_secret";
String urlString = API_URL + "gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 解析JSON响应,获取访问令牌
// 这里使用了第三方库JSON库来解析JSON数据,你可以根据需要选择其他方式
JSONObject jsonObject = new JSONObject(response.toString());
String accessToken = jsonObject.getString("access_token");
return accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 发送文本消息
public static void sendTextMessage(String accessToken, String corpId, String agentId, String userId, String content) {
String urlString = API_URL + "message/send?access_token=" + accessToken;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 构建请求参数
JSONObject params = new JSONObject();
params.put("touser", userId);
params.put("msgtype", "text");
JSONObject text = new JSONObject();
text.put("content", content);
params.put("text", text);
params.put("agentid", agentId);
params.put("safe", 0);
// 发送POST请求
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(params.toString().getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 请求成功
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 解析JSON响应
JSONObject jsonResponse = new JSONObject(response.toString());
int errorCode = jsonResponse.getInt("errcode");
String errorMessage = jsonResponse.getString("errmsg");
if (errorCode == 0) {
System.out.println("Message sent successfully!");
} else {
System.out.println("Failed to send message. Error code: " + errorCode + ", error message: " + errorMessage);
}
} else {
// 请求失败
System.out.println("Failed to send message. Response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码示例演示了如何获取访问令牌(access token)并使用该令牌发送文本消息到指定的用户。你需要将 `your_corp_id`、`your_corp_secret`、`your_agent_id`、`your_user_id` 替换为你自己的企业微信相关信息。此外,你还需要引入JSON库来解析和构建JSON数据。在示例中,我使用了一个名为 `JSONObject` 的类来完成这个任务,但你可以根据自己的需要选择其他库。
请注意,这只是一个简单的示例代码,实际使用中可能需要更多的逻辑和错误处理。你可以根据企业微信的开发文档进一步了解API的使用方法,并根据需要进行扩展和修改。