http的post请求出现401的错误,怎么解决

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

public class GetToken {
public static final String POST_URL = "https://c2bt4.maxuscloud.com/oauth/token";

/**
 * 调用Post接口
 */

public static void httpURLConnectionPOST(){
    try {
        URL url = new URL(POST_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        // post请求缓存设为false
        connection.setUseCaches(false);
        // 设置该HttpURLConnection实例是否自动执行重定向
        connection.setInstanceFollowRedirects(true);

        connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
        connection.connect();
        DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
        String param = "client_id=bc8f844701de11e98372fa163ed907b0&client_secret=cda0673501de11e98372fa163ed907b0&scope=read write&grant_type=client_credentials";
        dataout.writeBytes(param);
        dataout.flush();
        dataout.close();
        BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder(); // 用来存储响应数据

        // 循环读取流,若不到结尾处
        while ((line = bf.readLine()) != null) {
            //sb.append(bf.readLine());
            sb.append(line).append(System.getProperty("line.separator"));
        }
        bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
        connection.disconnect(); // 销毁连接
        System.out.println(sb.toString());

    }catch (Exception e){
        e.printStackTrace();
    }
}

public static void main(String[] args) throws UnknownHostException {
    httpURLConnectionPOST();
}

}
图片说明

2个回答

401就是服务端身份认证没有通过呀,看看账号密码是不是正确

1.检查账号密码
2.检查消息头
3.如果消息头有误,将返回的401消息中的消息头里的字段进行核对,把nonce拷贝进请求的消息头里再次请求

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐