以下代码,是想调用钉钉的通讯录信息,到C#的DGV,以做进一步展示,但在实际运行中,读取不到通讯录的用户信息,请帮我看看,哪里有问题,谢谢了;
using System;
using System.Data;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace SalaryCount
{
public partial class Form1 : Form
{
private string appKey = "dingqnybw1hbp4lqyeqp";
private string appSecret = "UfXT4o9RG0CdKIP2sXy8NhuimP24tQKGrBRYpkLo1R8y0PLy_yfeI7fbCQHDPbQZ";
private string accessToken;
private DataTable dtUsers;
public Form1()
{
InitializeComponent();
dtUsers = new DataTable();
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("Name");
dtUsers.Columns.Add("Department");
dataGridView1.DataSource = dtUsers;
}
private async void button1_Click(object sender, EventArgs e)
{
try
{
accessToken = await GetAccessTokenAsync(appKey, appSecret);
if (!string.IsNullOrEmpty(accessToken))
{
string departmentId = "1"; // 部门 ID,如果要获取全部部门,可以不设置
var userList = await FetchUserListAsync(accessToken, departmentId);
// 清空 dtUsers 中的数据
dtUsers.Rows.Clear();
// 将获取到的用户列表填充到 dtUsers 中
foreach (var user in userList)
{
dtUsers.Rows.Add(user.UserId, user.Name, user.Department);
}
}
else
{
MessageBox.Show("Failed to get access token.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async Task<string> GetAccessTokenAsync(string appKey, string appSecret)
{
using (var client = new HttpClient())
{
var requestUrl = $"https://oapi.dingtalk.com/gettoken?appkey={appKey}&appsecret={appSecret}";
var response = await client.GetAsync(requestUrl);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<dynamic>(json);
// 检查是否成功获取了 access token
if (result != null && result.access_token != null)
{
return result.access_token;
}
else
{
throw new Exception("Failed to get access token.");
}
}
}
private async Task<List<User>> FetchUserListAsync(string accessToken, string departmentId)
{
using (var client = new HttpClient())
{
var requestUrl = $"https://oapi.dingtalk.com/topapi/v2/user/list?access_token={accessToken}&dept_id={departmentId}&offset=0&size=10";
var response = await client.GetAsync(requestUrl);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<dynamic>(json);
// 检查结果是否为 null
if (result != null && result.result != null && result.result.list != null)
{
List<User> userList = new List<User>();
foreach (var user in result.result.list)
{
userList.Add(new User
{
UserId = user.UserId,
Name = user.Name,
Department = user.Department
});
}
return userList;
}
else
{
throw new Exception("没有用户列表");
}
}
}
}
public class User
{
public string UserId { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
}