记录环信IM使用restful接口时遇到的发送PUT请求失败的问题

文章讲述了开发者在使用环信修改用户密码接口时遇到的问题,原本设置为PUT请求却变成了GET,原因是Bearer头拼接时缺少空格。作者通过添加空格解决了问题,但未详述具体原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题发生在环信修改用户密码的接口上,接口如下

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,至于原因,没有找到可引用的内容。
因为token一般是可能带符号的随机字符串,而Bearer也是字符串,没有空格无法分割前缀和token,这里标点符号不适合用来作分割。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值