钉钉获取所有部门ID方法

获取部门,钉钉提供了两个API。
1.获取子部门ID列表
2.获取部门列表

1方式必须传递id(父部门ID),当我们想获得公司所有部门的信息的时候,我们用2方法,将id赋值为"",这样就可以返回所有部门的信息了,而不像1方法只返回传递的id的子部门id。

代码如下:
/**
* 获取公司所有部门ID
* @param accessToken 调用接口凭证
* @param id 父部门id
* @return
* @throws OApiException
*/
public static List<Object> getDepertmentId(String accessToken, String id) throws OApiException {
List<Object> depertmentIdList = new ArrayList<Object>();
String url = "";
if (id != null && !id.isEmpty()) {
url = Env.OAPI_HOST + "/department/list?" + "access_token=" + accessToken + "&id=" + id;
} else {
url = Env.OAPI_HOST + "/department/list?" + "access_token=" + accessToken + "&id=" + "";
}
JSONObject response = HttpHelper.httpGet(url);
JSONArray jsonArray = response.getJSONArray("department");
for (int i=0; i<jsonArray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
depertmentIdList.add(jsonObject.get("id").toString());
}
return depertmentIdList;
}



// get请求
public static JSONObject httpGet(String url) throws OApiException {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);

try {
response = httpClient.execute(httpGet, new BasicHttpContext());
if (response.getStatusLine().getStatusCode() != 200) {

System.out.println(
"request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");

JSONObject result = JSON.parseObject(resultStr);
if (result.getInteger("errcode") == 0) {
// result.remove("errcode");
// result.remove("errmsg");
return result;
} else {
System.out.println("request url=" + url + ",return value=");
System.out.println(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg");
throw new OApiException(errCode, errMsg);
}
}
} catch (IOException e) {
System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null)
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值