Guest User

Untitled

a guest
Aug 7th, 2022
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. public static boolean connectToServer() throws IOException,InterruptedException{
  2. HttpServer server = HttpServer.create();
  3. final String[] code = {""};
  4. HttpHandler httpHandler = new HttpHandler() {
  5. @Override
  6. public void handle(HttpExchange httpExchange) throws IOException{
  7. code[0] = httpExchange.getRequestURI().getQuery();
  8. String hello = "Got the code. Return back to your program.";
  9. if(code[0] == null || code[0].equals("") || code[0].contains("error=")) {
  10. hello = "Authorization code not found. Try again.";
  11. httpExchange.sendResponseHeaders(400, hello.length());
  12. }
  13. else httpExchange.sendResponseHeaders(200,hello.length());
  14. httpExchange.getResponseBody().write(hello.getBytes());
  15. httpExchange.getResponseBody().close();
  16. }
  17. };
  18. server.bind(new InetSocketAddress(8080),0);
  19. server.createContext("/", httpHandler);
  20. server.start();
  21. int time = 0;
  22. while(code[0].equals("") && time < 3000){
  23. Thread.sleep(10);
  24. time += 1;
  25. }
  26. if(code[0] == null || code[0].equals("") || code[0].contains("error="))
  27. return false;
  28. server.stop(10);
  29. HttpClient httpClient = HttpClient.newBuilder().build();
  30. HttpRequest httpRequest = HttpRequest.newBuilder()
  31. .uri(URI.create(authLink+"/api/token"))
  32. .POST(HttpRequest.BodyPublishers.ofString(String.format(
  33. "grant_type=authorization_code&%s&redirect_uri=%s",code[0],"http://localhost:8080"
  34. )))
  35. .headers("Content-Type","application/x-www-form-urlencoded","Authorization","Authorization: Basic <urlsafe_base64 encoded 1fd36c09884c424a9a80923c5760aeb9:887e4bba4c6243938352812f1ec463a7>")
  36. .build();
  37. HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
  38. System.out.println(response.statusCode()+" "+response.body());
  39. return true;
  40. }
Add Comment
Please, Sign In to add comment