Skip to content

Instantly share code, notes, and snippets.

@apoorvparijat
Created April 11, 2023 13:39
Show Gist options
  • Select an option

  • Save apoorvparijat/ef45fa24e95cb7411e433d323bf95ef8 to your computer and use it in GitHub Desktop.

Select an option

Save apoorvparijat/ef45fa24e95cb7411e433d323bf95ef8 to your computer and use it in GitHub Desktop.
How to use injected variable in AsyncHandler
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