### Creating Simple HTTP Server with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet illustrates how to create a basic HTTP server using AsyncHttpServer. It sets up a GET route for the root path ("/") that responds with "Hello!!!". The server listens on port 5000. Dependencies include AsyncHttpServer and HttpServerRequestCallback. ```Java AsyncHttpServer server = new AsyncHttpServer(); List _sockets = new ArrayList(); server.get("/", new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { response.send("Hello!!!"); } }); // listen on port 5000 server.listen(5000); // browsing http://localhost:5000 will return Hello!!! ``` -------------------------------- ### Adding AndroidAsync Dependency with Gradle Source: https://github.com/koush/androidasync/blob/master/README.md This Groovy snippet demonstrates how to declare the AndroidAsync library as a compile-time dependency in a Gradle build script, typically `build.gradle`. The `2.+` version specifies that any version starting with 2 will be used, allowing for minor updates. ```groovy dependencies { compile 'com.koushikdutta.async:androidasync:2.+' } ``` -------------------------------- ### Downloading URL Content to String using AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java code snippet illustrates how to perform an asynchronous HTTP GET request to download content from a specified URL and receive it as a `String`. It uses a callback to handle the completion, including error handling and printing the result. ```java // url is the URL to download. AsyncHttpClient.getDefaultInstance().getString(url, new AsyncHttpClient.StringCallback() { // Callback is invoked with any exceptions/errors, and the result, if available. @Override public void onCompleted(Exception e, AsyncHttpResponse response, String result) { if (e != null) { e.printStackTrace(); return; } System.out.println("I got a string: " + result); } }); ``` -------------------------------- ### Downloading JSON Object from URL using AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java example demonstrates how to fetch JSON data from a URL and parse it into a `JSONObject` asynchronously. The `JSONObjectCallback` handles both successful responses and any exceptions during the download or parsing process, printing the resulting JSON object. ```java // url is the URL to download. AsyncHttpClient.getDefaultInstance().getJSONObject(url, new AsyncHttpClient.JSONObjectCallback() { // Callback is invoked with any exceptions/errors, and the result, if available. @Override public void onCompleted(Exception e, AsyncHttpResponse response, JSONObject result) { if (e != null) { e.printStackTrace(); return; } System.out.println("I got a JSONObject: " + result); } }); ``` -------------------------------- ### Performing Multipart Form Data Uploads with AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java example demonstrates how to construct and send a multipart/form-data POST request using `AsyncHttpPost`. It allows adding both file parts and string parts to the request body, useful for uploading files and associated form data to a server. ```java AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html"); MultipartFormDataBody body = new MultipartFormDataBody(); body.addFilePart("my-file", new File("/path/to/file.txt"); body.addStringPart("foo", "bar"); post.setBody(body); AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback(){ @Override public void onCompleted(Exception ex, AsyncHttpResponse source, String result) { if (ex != null) { ex.printStackTrace(); return; } System.out.println("Server says: " + result); } }); ``` -------------------------------- ### Creating WebSocket Client with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet demonstrates how to establish a WebSocket connection using AsyncHttpClient. It shows how to handle connection completion, send string and byte data, and set callbacks for incoming string and binary data. Dependencies include AsyncHttpClient and WebSocketConnectCallback. ```Java AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { ex.printStackTrace(); return; } webSocket.send("a string"); webSocket.send(new byte[10]); webSocket.setStringCallback(new StringCallback() { public void onStringAvailable(String s) { System.out.println("I got a string: " + s); } }); webSocket.setDataCallback(new DataCallback() { public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) { System.out.println("I got some bytes!"); // note that this data has been read byteBufferList.recycle(); } }); } }); ``` -------------------------------- ### Downloading URL Content to File using AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java code demonstrates how to download content from a URL directly to a local file. The `getFile` method takes the URL and desired filename, and the `FileCallback` provides the resulting `File` object upon completion, allowing access to its absolute path. ```java AsyncHttpClient.getDefaultInstance().getFile(url, filename, new AsyncHttpClient.FileCallback() { @Override public void onCompleted(Exception e, AsyncHttpResponse response, File result) { if (e != null) { e.printStackTrace(); return; } System.out.println("my file is available at: " + result.getAbsolutePath()); } }); ``` -------------------------------- ### Creating WebSocket Server with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet shows how to implement a WebSocket server using AsyncHttpServer. It listens for WebSocket connections on the "/live" path, adds connected sockets to a list, and sets up callbacks for connection closure and incoming string messages. It also demonstrates broadcasting messages to all connected clients. Dependencies include AsyncHttpServer, WebSocket, AsyncHttpServer.WebSocketRequestCallback, CompletedCallback, and StringCallback. ```Java AsyncHttpServer httpServer = new AsyncHttpServer(); httpServer.listen(AsyncServer.getDefault(), port); httpServer.websocket("/live", new AsyncHttpServer.WebSocketRequestCallback() { @Override public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) { _sockets.add(webSocket); //Use this to clean up any references to your websocket webSocket.setClosedCallback(new CompletedCallback() { @Override public void onCompleted(Exception ex) { try { if (ex != null) Log.e("WebSocket", "An error occurred", ex); } finally { _sockets.remove(webSocket); } } }); webSocket.setStringCallback(new StringCallback() { @Override public void onStringAvailable(String s) { if ("Hello Server".equals(s)) webSocket.send("Welcome Client!"); } }); } }); //..Sometime later, broadcast! for (WebSocket socket : _sockets) socket.send("Fireball!"); ``` -------------------------------- ### Adding AndroidAsync Dependency with Maven Source: https://github.com/koush/androidasync/blob/master/README.md This XML snippet shows how to include the AndroidAsync library as a dependency in a Maven project's `pom.xml` file. Users should replace `(insert latest version)` with the actual latest version number to ensure they are using the most up-to-date library. ```xml com.koushikdutta.async androidasync (insert latest version) ``` -------------------------------- ### Configuring HTTP Response Caching with AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java snippet shows how to enable and configure response caching for `AsyncHttpClient`. It specifies the client instance, the directory for storing cache files, and the maximum size of the cache in bytes, improving performance for repeated requests. ```java // arguments are the http client, the directory to store cache files, // and the size of the cache in bytes ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(), getFileStreamPath("asynccache"), 1024 * 1024 * 10); ``` -------------------------------- ### Blocking Future Result Retrieval with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet demonstrates how to retrieve the result of an asynchronous operation using a Future in a blocking manner. The get() method will pause execution until the result is available or an error occurs. It requires a Future object, typically obtained from an AsyncHttpClient client. ```Java Future string = client.getString("http://foo.com/hello.txt"); // this will block, and may also throw if there was an error! String value = string.get(); ``` -------------------------------- ### Downloading JSON Array from URL using AndroidAsync Source: https://github.com/koush/androidasync/blob/master/README.md This Java snippet shows how to retrieve JSON data from a URL and parse it into a `JSONArray` asynchronously. Similar to `JSONObjectCallback`, the `JSONArrayCallback` manages the completion, including error handling, and outputs the received JSON array. ```java // url is the URL to download. AsyncHttpClient.getDefaultInstance().getJSONArray(url, new AsyncHttpClient.JSONArrayCallback() { // Callback is invoked with any exceptions/errors, and the result, if available. @Override public void onCompleted(Exception e, AsyncHttpResponse response, JSONArray result) { if (e != null) { e.printStackTrace(); return; } System.out.println("I got a JSONArray: " + result); } }); ``` -------------------------------- ### Attaching Callback to Future with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet shows how to attach a callback to a Future to handle the asynchronous operation's completion. The onCompleted method of the FutureCallback is invoked when the result is ready or an exception occurs, allowing non-blocking processing of the outcome. ```Java Future string = client.getString("http://foo.com/hello.txt"); string.setCallback(new FutureCallback() { @Override public void onCompleted(Exception e, String result) { System.out.println(result); } }); ``` -------------------------------- ### Chaining Future Callbacks with AndroidAsync in Java Source: https://github.com/koush/androidasync/blob/master/README.md This snippet demonstrates a more concise way to attach a callback directly to the Future returned by an asynchronous method call. This chaining pattern improves readability by reducing the need for an intermediate variable for the Future object, directly handling the result or error upon completion. ```Java client.getString("http://foo.com/hello.txt") .setCallback(new FutureCallback() { @Override public void onCompleted(Exception e, String result) { System.out.println(result); } }); ``` -------------------------------- ### Adding AndroidAsync Kotlin Dependency (Maven) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync-Kotlin/README.md This XML snippet shows the Maven dependency configuration required to include the `androidasync-kotlin` library in your project. Replace `(insert latest version)` with the actual latest version number to ensure proper integration. ```xml com.koushikdutta.async androidasync-kotlin (insert latest version) ``` -------------------------------- ### Adding AndroidAsync Kotlin Dependency (Gradle) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync-Kotlin/README.md This Groovy snippet demonstrates how to add the `androidasync-kotlin` library as a compile-time dependency in a Gradle build file. Remember to substitute `` with the current stable release. ```groovy dependencies { compile 'com.koushikdutta.async:androidasync-kotlin:' } ``` -------------------------------- ### Fetching Data Sequentially with Ion and Coroutines (Kotlin) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync-Kotlin/README.md This Kotlin suspend function demonstrates fetching two different `robots.txt` files sequentially using Ion and Kotlin Coroutines. Each `await()` call suspends the coroutine until the previous network request completes, ensuring ordered execution. ```kotlin suspend fun getTheRobotsTxt() { val googleRobots = Ion.with(context) .load("https://google.com/robots.txt") .asString() .await() val githubRobots = Ion.with(context) .load("https://github.com/robots.txt") .asString() .await() return googleRobots + githubRobots } ``` -------------------------------- ### Fetching Data Concurrently with Ion and Coroutines (Kotlin) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync-Kotlin/README.md This Kotlin suspend function illustrates how to initiate multiple Ion network requests concurrently before awaiting their results. By calling `await()` only after both requests are initiated, the operations can run in parallel, potentially improving performance. ```kotlin suspend fun getTheRobotsTxt() { val googleRobots = Ion.with(context) .load("https://google.com/robots.txt") .asString() val githubRobots = Ion.with(context) .load("https://github.com/robots.txt") .asString() return googleRobots.await() + githubRobots.await() } ``` -------------------------------- ### Keeping WebView JavaScript Interface Members - ProGuard Source: https://github.com/koush/androidasync/blob/master/AndroidAsyncSample/proguard-project.txt This ProGuard rule, when uncommented, ensures that all public members of a specified JavaScript interface class for WebView are preserved during obfuscation and optimization. Replace 'fqcn.of.javascript.interface.for.webview' with the actual fully qualified class name of your JavaScript interface. ```ProGuard -keepclassmembers class fqcn.of.javascript.interface.for.webview { public *; } ``` -------------------------------- ### Keeping AndroidAsync TapCallback Class (ProGuard) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync/proguard-project.txt This rule prevents obfuscation of classes extending `com.koushikdutta.async.TapCallback`. It ensures that all public, protected, and private members of such classes are preserved during ProGuard processing, which is crucial for their runtime functionality and reflection-based operations. ```ProGuard -keep class * extends com.koushikdutta.async.TapCallback { public protected private *; } ``` -------------------------------- ### Keeping JavaScript Interface for WebView (ProGuard) Source: https://github.com/koush/androidasync/blob/master/AndroidAsync/proguard-project.txt This commented-out rule demonstrates how to prevent obfuscation of a JavaScript interface class used with WebView. It ensures all public members of the specified class are kept, allowing JavaScript to interact with them without issues after ProGuard processing. ```ProGuard -keepclassmembers class fqcn.of.javascript.interface.for.webview { public *; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.