카테고리 없음

JWT client - authenticate sample code

OJR 2023. 3. 27. 15:51
import okhttp3.*;
import java.io.IOException;

public class JWTClient {
    public static void main(String[] args) {
        String url = "https://example.com/api/authenticate";
        String username = "myusername";
        String password = "mypassword";

        // Create a JSON payload with the username and password
        String json = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";

        // Create a new OkHttpClient
        OkHttpClient client = new OkHttpClient();

        // Create a new RequestBody with the JSON payload
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        // Create a new POST request with the RequestBody
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try {
            // Execute the request and get the response
            Response response = client.newCall(request).execute();

            // Get the response body as a string
            String responseBody = response.body().string();

            // Parse the JWT token from the response body
            String token = responseBody.substring(10, responseBody.length() - 2);

            // Print the token
            System.out.println("JWT Token: " + token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
반응형