问题发生在环信修改用户密码的接口上,接口如下
PUT https://{host}/{org_name}/{app_name}/users/{username}/password
token是已经存在于redis中的,这里我的代码中是直接取的。
@Override
public boolean modifyPassword (String username, String password) throws IOException {
HashMap<String,String> map =new HashMap<> ();
URL url = new URL ("https://" + host + "/" + orgName + "/" + appName + "/users/" + username + "/password");
HttpURLConnection connection = (HttpURLConnection) url.openConnection ();
// 设置请求方法为PUT
connection.setRequestMethod ("PUT");
// 设置请求头部信息
connection.setRequestProperty("Accept", "application/json");
String token = (String) redisTemplate.opsForValue ().get (RedisKeyConfig.IM_TOKEN);
connection.setRequestProperty ("Authorization","Bearer"+token);
// 开启输出流,写入请求体数据
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
String requestBody = "{\"newpassword\": \""+password+"\"}";
outputStream.write(requestBody.getBytes());
outputStream.flush();
// 发送请求并获取响应
int responseCode = connection.getResponseCode();
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader (connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String substring = response.substring (1, response.length () - 1);
System.out.println (substring);
connection.disconnect();
if(substring.contains ("set user password")){
return true;
}
return false;
}
按理来说,到这里请求是符合环信接口要求的,但是神奇的事情发生了,这里显示发送了一个get请求,但我设置的是put请求。这次请求不出意外的返回了错误码401。
本以为是请求方式设置没有成功,亦或者是connection.setRequestProperty ("Authorization","Bearer "+redisTemplate.opsForValue ().get (RedisKeyConfig.IM_TOKEN));
的写法导致token有问题。
在排查一圈后注意到了AI的一句话。
加上空格后问题果然解决了。
然后了解了一下,Bearer后面必须带空格,然后才能拼接token,至于原因,没有找到可引用的内容。