Java 8 - 使用 Bearer 令牌的 POST 请求失败并显示 401

问题描述 投票:0回答:1

请注意,我必须使用 java 8 来完成这项工作。 首先对中间件网关进行 POST 身份验证并获取 accessToken。使用相同的访问令牌,我向服务端点 url 执行 POST。我在请求属性中设置了所有必需的标头,但收到 401 响应。我试图不使用任何外部库,并试图做到这一点是纯java。任何帮助表示赞赏。

我得到的确切错误是{“error”:“invalid_grant”,“error_description”:“令牌未找到,已过期或无效”,.....} 正如您在下面看到的,我正在设置访问令牌,这段代码中还缺少其他内容吗? 下面是代码:

 private static void sendPOST(){
    String jsonStr = getPostDataJson();     
    InputStream stream = null;      
    BufferedReader reader = null;
    HttpURLConnection conn = null;
    if(accessToken != null && accessToken.length()>0) {
        try {
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Bearer " + accessToken);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", String.valueOf(jsonStr.length()));
            conn.setRequestMethod("POST");              
            conn.setUseCaches(false);               
            conn.connect();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(jsonStr);
            writer.flush();
            writer.close();
            os.close();
            
            int responseCode = conn.getResponseCode();
            System.out.println("Status Code :" + responseCode);     
            
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                stream = conn.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(stream));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } else {
                System.out.println("Post request encountered error." + responseCode);
            }
        
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }}}
post java-8 bearer-token http-status-code-401 unauthorized
1个回答
0
投票

问题已解决,accessToken 标头有错误。

© www.soinside.com 2019 - 2024. All rights reserved.