Skip to content

Instantly share code, notes, and snippets.

@rajkrrsingh
Created August 2, 2020 23:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajkrrsingh/9a8a93c1be32034d8eda4be2fca1d036 to your computer and use it in GitHub Desktop.
Save rajkrrsingh/9a8a93c1be32034d8eda4be2fca1d036 to your computer and use it in GitHub Desktop.
Java11 HttpClient to test the jwt authentication
package org.example;


import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Client {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)

                .connectTimeout(Duration.ofSeconds(10))
                .build();

        Map<Object, Object> params = new HashMap<>();
        params.put("user","raj@example.org");
        params.put("passwd","testpass");

        HttpRequest httpRequest = createtHttpRequest(params,null);

        CompletableFuture<HttpResponse<String>> httpResponse = null;

        httpResponse = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());

        String token = null;
        if (httpResponse != null) {
                printHttpResponseHeaderAndBody(httpResponse);
                token = getToken(httpResponse);
            System.out.println("Token Recieved : "+token);
        } else {
            System.err.println("Error while processing the response");
        }


        HttpRequest httpRequestWithToken = createtHttpRequest(params,token);

        CompletableFuture<HttpResponse<String>> httpResponse1 = null;
        httpResponse1 =
                httpClient.sendAsync(httpRequestWithToken, HttpResponse.BodyHandlers.ofString());

        if (httpResponse1 != null) {
            printHttpResponseHeaderAndBody(httpResponse1);
        }


    }

    private static String getToken(CompletableFuture<HttpResponse<String>> httpResponse) {
        String token = null;
        try {
            token = httpResponse.get().headers().firstValue("token").get();
        } catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    private static void printHttpResponseHeaderAndBody(CompletableFuture<HttpResponse<String>> httpResponse)  {
        try {
            System.out.println("############Printing Response Header###############################");
            httpResponse.get().headers().map().forEach((x, y) -> System.out.println(x + ":" + y));
            System.out.println("###################################################################");
            System.out.println("#####################Printing Response Body #######################");
            System.out.println(httpResponse.get().body());
            System.out.println("###################################################################");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static HttpRequest createtHttpRequest(Map<Object, Object> params,String token) {
        HttpRequest.Builder httpRequestBuilder = HttpRequest.newBuilder()
                .POST(ofFormData(params))
                .uri(URI.create("http://localhost:8080/login"))
                .setHeader("User-Agent", "Java11_JWT_Test_Client")
                .header("Content-Type", "application/x-www-form-urlencoded");

        if (token != null) {
            httpRequestBuilder.header("Token",token);
        }

        return httpRequestBuilder.build();
    }

    public static HttpRequest.BodyPublisher ofFormData(Map<Object, Object> data) {
        var builder = new StringBuilder();
        for (Map.Entry<Object, Object> entry : data.entrySet()) {
            if (builder.length() > 0) {
                builder.append("&");
            }
            builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
            builder.append("=");
            builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
        }
        return HttpRequest.BodyPublishers.ofString(builder.toString());
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment