获取部门,钉钉提供了两个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;
}