Created
April 11, 2023 13:39
-
-
Save apoorvparijat/ef45fa24e95cb7411e433d323bf95ef8 to your computer and use it in GitHub Desktop.
How to use injected variable in AsyncHandler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.asynchttpclient.*; | |
| import java.util.concurrent.Future; | |
| public class MainClass { | |
| private final String injectedVariable = "Hello, AsyncHandler!"; | |
| public static void main(String[] args) { | |
| MainClass mainClass = new MainClass(); | |
| mainClass.sendRequest(); | |
| } | |
| public void sendRequest() { | |
| try (AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient()) { | |
| Request request = new RequestBuilder("GET") | |
| .setUrl("https://jsonplaceholder.typicode.com/posts/1") | |
| .build(); | |
| MyAsyncHandler myAsyncHandler = new MyAsyncHandler(injectedVariable); | |
| Future<String> future = asyncHttpClient.executeRequest(request, myAsyncHandler); | |
| String responseBody = future.get(); | |
| System.out.println("Response body: " + responseBody); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| } | |
| class MyAsyncHandler extends AsyncCompletionHandler<String> { | |
| private final String injectedVariable; | |
| public MyAsyncHandler(String injectedVariable) { | |
| this.injectedVariable = injectedVariable; | |
| } | |
| @Override | |
| public String onCompleted(Response response) throws Exception { | |
| System.out.println("Injected variable: " + injectedVariable); | |
| return response.getResponseBody(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment