카테고리 없음

JWT client - api request (token 활용) sample code

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

public class ProtectedResourceClient {
    public static void main(String[] args) {
        String url = "https://example.com/api/protected/resource";

        // Set the JWT token in the Authorization header
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
        String headerValue = "Bearer " + token;

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

        // Create a new GET request with the Authorization header
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", headerValue)
                .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();

            // Do something with the response
            System.out.println("Response: " + responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
반응형