java - 如何将 Exchange.getRequestURI().getQuery() 的结果存储在变量中并使用它来获取授权码

标签 java http post oauth-2.0 access-token

我正在尝试实现此阶段的项目 - https://hyperskill.org/projects/62/stages/337/implement 。 我需要将 String code = Exchange.getRequestURI().getQuery(); 的结果存储在变量中,并在 POST 请求中使用它。

POST(HttpRequest.BodyPublishers.ofString("client_id="+ CLIENT_ID + "&client_secret="+ CLIENT_SECRET+ "&grant_type="+ GRANT_TYPE + "&code="+ 代码 + "&redirect_uri="+ REDIRECT_URI))

但我不能这样做,因为它不存储在 server.createContext 之外的可用空间中。 也许我想做错事?谁能帮我吗?


    private static final String CLIENT_ID = "da072c60fcee469e8b0f4140aa4480d5";
    private static final String CLIENT_SECRET = "8ada13093c704487b57c3a660448884e";
    private static final String AUTHORIZE_ADDRESS = "https://accounts.spotify.com/authorize";
    private static final String RESPONSE_TYPE = "code";
    private static final String TOKEN_ADDRESS = "https://accounts.spotify.com/api/token";
    private static final String GRANT_TYPE = "authorization_code";
    private static final String CODE = "";
    private static final String REDIRECT_URI = "http://localhost:8080";
    private static final String ANSWER_DENIED_ACCESS = "Please, provide access for application.";

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        boolean successfulAccess = false;

        while (sc.hasNext()) {
            String input = sc.next();
            switch (input) {
                case "auth":
                    server();
                    request();
                    successfulAccess = true;
                    System.out.println("---SUCCESS---");
                    break;
            }
        }
    }

    private static void server() throws IOException {
        HttpServer server = HttpServer.create();
        server.bind(new InetSocketAddress(8080), 0);

        server.start();

        System.out.println("use this link to request the access code:");
        System.out.println(AUTHORIZE_ADDRESS
                + "?client_id=" + CLIENT_ID
                + "&redirect_uri=" + REDIRECT_URI
                + "&response_type=" + RESPONSE_TYPE);
        System.out.println("waiting for code...");

        server.createContext("/",
                exchange -> {
                    String code = exchange.getRequestURI().getQuery();
                    String result = "";
                    String answer = "";

                    if (code.contains("code")) {
                        result = "Got the code. Return back to your program.";
                        answer = "code received";
                    } else {
                        result = "Not found authorization code. Try again.";
                        answer = "code didn't received";
                    }

                    exchange.sendResponseHeaders(200, result.length());
                    exchange.getResponseBody().write(result.getBytes());
                    exchange.getResponseBody().close();

                    System.out.println(answer);
                }
        );

        server.stop(10);
    }

    private static void request() throws IOException, InterruptedException {

        System.out.println("making http request for access_token...");

        HttpRequest request = HttpRequest.newBuilder()
                .POST(HttpRequest.BodyPublishers.ofString(
                        "client_id=" + CLIENT_ID
                                + "&client_secret=" + CLIENT_SECRET
                                + "&grant_type=" + GRANT_TYPE
                                + "&code=" + CODE
                                + "&redirect_uri=" + REDIRECT_URI))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .uri(URI.create(TOKEN_ADDRESS))
                .build();

        HttpClient client = HttpClient.newBuilder().build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("response:");
        System.out.println(response.body());
    }
}```

最佳答案

我需要使用 Thread.sleep 进行 while 循环,而不是通常可以将代码存储在变量中。像这样:

                exchange -> {
                    String code = exchange.getRequestURI().getQuery();
                    String result = "";
                    String answer = "";

                    if (code != null && code.contains("code")) {
                        CODE = code.substring(5);
                        result = "Got the code. Return back to your program.";
                        answer = "code received";
                    } else {
                        result = "Not found authorization code. Try again.";
                        answer = "code not received";
                    }

                    exchange.sendResponseHeaders(200, result.length());
                    exchange.getResponseBody().write(result.getBytes());
                    exchange.getResponseBody().close();

                    System.out.println(answer);
                }
        );
        while (CODE.equals("")) {
            Thread.sleep(10);
        }

        server.stop(10);```

关于java - 如何将 Exchange.getRequestURI().getQuery() 的结果存储在变量中并使用它来获取授权码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61265292/

相关文章:

JAVA正则表达式在字符和数字之间添加空格

java - 用于泛型类扩展的 Mockito/Powermock 类构造

rest - 对于已处理的 POST 请求,最合适的 HTTP 状态代码是什么?

java - 在 JBoss Seam 中使用 post 参数重定向到外部网站?

java - Spring security REST 不处理登录请求(404)

node.js - 将 header 添加到 307 重定向

javascript - Angular 1.6 $http.get 无法读取 json

python - XML SOAP POST 错误,我做错了什么?

java - 在 JsonObject 上使用 getAsJsonArray

java - ArrayList 调整当前底层数组的大小或创建一个新数组?