之前调用环信接口时,因为其他接口参数都是application/json格式,用的好几种方法都没问题。后来发现其中一个接口 修改用户属性/{org_name}/{app_name}/metadata/user/{username} 使用的是application/x-www-form-urlencoded格式,尝试了几种方法都不行。后来自己慢慢琢磨出写法。
先上调用application/json格式接口写法,以注册用户为例
emChatConfig.getPrefixUrl()为路径前缀,写在配置文件中
public boolean addUser(String userHxName, String password) {
try {
JSONArray body = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", userHxName);
jsonObject.put("password", password);
body.add(jsonObject);
HttpEntity httpEntity = new HttpEntity(body, emChatConfig.getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(emChatConfig.getPrefixUrl() + "users", httpEntity, JSONObject.class);
if (responseEntity.getStatusCodeValue() == 200) {
return true;
}
log.error("环信注册用户失败,返回接口为{},用户ID{},密码{}", responseEntity, userHxName, password);
} catch (RestClientException e) {
e.printStackTrace();
log.error("环信注册用户异常", e);
}
return false;
}
下面是修改用户属性接口写法
public Boolean updateUserAttribute(String userHxName, UserAttribute userAttribute) {
try {
//实体类转换成参数
MultiValueMap<String, Object> parameters = setConditionMap(userAttribute);
HttpEntity httpEntity = new HttpEntity(parameters, emChatConfig.getHttpHeaders(MediaType.APPLICATION_FORM_URLENCODED));
ResponseEntity responseEntity = restTemplate.exchange(emChatConfig.getPrefixUrl() + "metadata/user/{username}", HttpMethod.PUT, httpEntity, JSONObject.class, userHxName);
System.out.println(responseEntity);
if (responseEntity.getStatusCodeValue() == 200) {
return true;
}
log.error("修改用户属性失败,返回接口为{},用户ID{},用户属性{}", responseEntity, userHxName, userAttribute);
} catch (RestClientException e) {
e.printStackTrace();
log.error("修改用户属性异常---", e);
}
return false;
}
UserAttribute为用户属性,其中属性可以自己编辑,不一定要按照环信给的属性编辑。