Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static boolean connectToServer() throws IOException,InterruptedException{
- HttpServer server = HttpServer.create();
- final String[] code = {""};
- HttpHandler httpHandler = new HttpHandler() {
- @Override
- public void handle(HttpExchange httpExchange) throws IOException{
- code[0] = httpExchange.getRequestURI().getQuery();
- String hello = "Got the code. Return back to your program.";
- if(code[0] == null || code[0].equals("") || code[0].contains("error=")) {
- hello = "Authorization code not found. Try again.";
- httpExchange.sendResponseHeaders(400, hello.length());
- }
- else httpExchange.sendResponseHeaders(200,hello.length());
- httpExchange.getResponseBody().write(hello.getBytes());
- httpExchange.getResponseBody().close();
- }
- };
- server.bind(new InetSocketAddress(8080),0);
- server.createContext("/", httpHandler);
- server.start();
- int time = 0;
- while(code[0].equals("") && time < 3000){
- Thread.sleep(10);
- time += 1;
- }
- if(code[0] == null || code[0].equals("") || code[0].contains("error="))
- return false;
- server.stop(10);
- HttpClient httpClient = HttpClient.newBuilder().build();
- HttpRequest httpRequest = HttpRequest.newBuilder()
- .uri(URI.create(authLink+"/api/token"))
- .POST(HttpRequest.BodyPublishers.ofString(String.format(
- "grant_type=authorization_code&%s&redirect_uri=%s",code[0],"http://localhost:8080"
- )))
- .headers("Content-Type","application/x-www-form-urlencoded","Authorization","Authorization: Basic <urlsafe_base64 encoded 1fd36c09884c424a9a80923c5760aeb9:887e4bba4c6243938352812f1ec463a7>")
- .build();
- HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
- System.out.println(response.statusCode()+" "+response.body());
- return true;
- }
Add Comment
Please, Sign In to add comment