{"id":13471775,"url":"https://github.com/AsyncHttpClient/async-http-client","last_synced_at":"2025-03-26T14:32:29.582Z","repository":{"id":37335545,"uuid":"1450115","full_name":"AsyncHttpClient/async-http-client","owner":"AsyncHttpClient","description":"Asynchronous Http and WebSocket Client library for Java ","archived":false,"fork":false,"pushed_at":"2024-10-29T20:38:35.000Z","size":19028,"stargazers_count":6287,"open_issues_count":109,"forks_count":1591,"subscribers_count":352,"default_branch":"main","last_synced_at":"2024-10-29T22:50:06.454Z","etag":null,"topics":["ahc","async","asynchttpclient","http-client","java","netty"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AsyncHttpClient.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2011-03-07T13:41:46.000Z","updated_at":"2024-10-29T20:37:41.000Z","dependencies_parsed_at":"2023-12-22T19:23:03.060Z","dependency_job_id":"92340bda-cf5a-4473-9ee4-62a9d0120839","html_url":"https://github.com/AsyncHttpClient/async-http-client","commit_stats":{"total_commits":3950,"total_committers":233,"mean_commits":"16.952789699570815","dds":0.6678481012658228,"last_synced_commit":"c4812b22a4a1c2e3e0e8bdba0f5103f60a54cc86"},"previous_names":[],"tags_count":285,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AsyncHttpClient%2Fasync-http-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AsyncHttpClient%2Fasync-http-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AsyncHttpClient%2Fasync-http-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AsyncHttpClient%2Fasync-http-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AsyncHttpClient","download_url":"https://codeload.github.com/AsyncHttpClient/async-http-client/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245377920,"owners_count":20605374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ahc","async","asynchttpclient","http-client","java","netty"],"created_at":"2024-07-31T16:00:49.178Z","updated_at":"2025-03-26T14:32:29.576Z","avatar_url":"https://github.com/AsyncHttpClient.png","language":"Java","readme":"# Async Http Client \n[![Build](https://github.com/AsyncHttpClient/async-http-client/actions/workflows/builds.yml/badge.svg)](https://github.com/AsyncHttpClient/async-http-client/actions/workflows/builds.yml)\n![Maven Central](https://img.shields.io/maven-central/v/org.asynchttpclient/async-http-client)\n\nFollow [@AsyncHttpClient](https://twitter.com/AsyncHttpClient) on Twitter.\n\nThe AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and asynchronously process HTTP responses.\nThe library also supports the WebSocket Protocol.\n\nIt's built on top of [Netty](https://github.com/netty/netty). It's compiled with Java 11.\n\n## Installation\n\nBinaries are deployed on Maven Central.\nAdd a dependency on the main AsyncHttpClient artifact:\n\nMaven:\n```xml\n\u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.asynchttpclient\u003c/groupId\u003e\n        \u003cartifactId\u003easync-http-client\u003c/artifactId\u003e\n        \u003cversion\u003e3.0.1\u003c/version\u003e\n    \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\nGradle:\n```groovy\ndependencies {\n    implementation 'org.asynchttpclient:async-http-client:3.0.1'\n}\n```\n\n### Dsl\n\nImport the Dsl helpers to use convenient methods to bootstrap components:\n\n```java\nimport static org.asynchttpclient.Dsl.*;\n```\n\n### Client\n\n```java\nimport static org.asynchttpclient.Dsl.*;\n\nAsyncHttpClient asyncHttpClient=asyncHttpClient();\n```\n\nAsyncHttpClient instances must be closed (call the `close` method) once you're done with them, typically when shutting down your application.\nIf you don't, you'll experience threads hanging and resource leaks.\n\nAsyncHttpClient instances are intended to be global resources that share the same lifecycle as the application.\nTypically, AHC will usually underperform if you create a new client for each request, as it will create new threads and connection pools for each.\nIt's possible to create shared resources (EventLoop and Timer) beforehand and pass them to multiple client instances in the config. You'll then be responsible for closing\nthose shared resources.\n\n## Configuration\n\nFinally, you can also configure the AsyncHttpClient instance via its AsyncHttpClientConfig object:\n\n```java\nimport static org.asynchttpclient.Dsl.*;\n\nAsyncHttpClient c=asyncHttpClient(config().setProxyServer(proxyServer(\"127.0.0.1\",38080)));\n```\n\n## HTTP\n\n### Sending Requests\n\n### Basics\n\nAHC provides 2 APIs for defining requests: bound and unbound.\n`AsyncHttpClient` and Dsl` provide methods for standard HTTP methods (POST, PUT, etc) but you can also pass a custom one.\n\n```java\nimport org.asynchttpclient.*;\n\n// bound\nFuture\u003cResponse\u003e whenResponse=asyncHttpClient.prepareGet(\"http://www.example.com/\").execute();\n\n// unbound\n        Request request=get(\"http://www.example.com/\").build();\n        Future\u003cResponse\u003e whenResponse=asyncHttpClient.executeRequest(request);\n```\n\n#### Setting Request Body\n\nUse the `setBody` method to add a body to the request.\n\nThis body can be of type:\n\n* `java.io.File`\n* `byte[]`\n* `List\u003cbyte[]\u003e`\n* `String`\n* `java.nio.ByteBuffer`\n* `java.io.InputStream`\n* `Publisher\u003cio.netty.buffer.ByteBuf\u003e`\n* `org.asynchttpclient.request.body.generator.BodyGenerator`\n\n`BodyGenerator` is a generic abstraction that let you create request bodies on the fly.\nHave a look at `FeedableBodyGenerator` if you're looking for a way to pass requests chunks on the fly.\n\n#### Multipart\n\nUse the `addBodyPart` method to add a multipart part to the request.\n\nThis part can be of type:\n\n* `ByteArrayPart`\n* `FilePart`\n* `InputStreamPart`\n* `StringPart`\n\n### Dealing with Responses\n\n#### Blocking on the Future\n\n`execute` methods return a `java.util.concurrent.Future`. You can simply block the calling thread to get the response.\n\n```java\nFuture\u003cResponse\u003e whenResponse=asyncHttpClient.prepareGet(\"http://www.example.com/\").execute();\n        Response response=whenResponse.get();\n```\n\nThis is useful for debugging but you'll most likely hurt performance or create bugs when running such code on production.\nThe point of using a non blocking client is to *NOT BLOCK* the calling thread!\n\n### Setting callbacks on the ListenableFuture\n\n`execute` methods actually return a `org.asynchttpclient.ListenableFuture` similar to Guava's.\nYou can configure listeners to be notified of the Future's completion.\n\n```java\n        ListenableFuture\u003cResponse\u003e whenResponse = ???;\n        Runnable callback = () - \u003e {\n            try {\n               Response response = whenResponse.get();\n               System.out.println(response);\n            } catch (InterruptedException | ExecutionException e) {\n               e.printStackTrace();\n            }\n        };\n\n        java.util.concurrent.Executor executor = ???;\n        whenResponse.addListener(() - \u003e ??? , executor);\n```\n\nIf the `executor` parameter is null, callback will be executed in the IO thread.\nYou *MUST NEVER PERFORM BLOCKING* operations in there, typically sending another request and block on a future.\n\n#### Using custom AsyncHandlers\n\n`execute` methods can take an `org.asynchttpclient.AsyncHandler` to be notified on the different events, such as receiving the status, the headers and body chunks.\nWhen you don't specify one, AHC will use a `org.asynchttpclient.AsyncCompletionHandler`;\n\n`AsyncHandler` methods can let you abort processing early (return `AsyncHandler.State.ABORT`) and can let you return a computation result from `onCompleted` that will be used\nas the Future's result.\nSee `AsyncCompletionHandler` implementation as an example.\n\nThe below sample just capture the response status and skips processing the response body chunks.\n\nNote that returning `ABORT` closes the underlying connection.\n\n```java\nimport static org.asynchttpclient.Dsl.*;\n\nimport org.asynchttpclient.*;\nimport io.netty.handler.codec.http.HttpHeaders;\n\nFuture\u003cInteger\u003e whenStatusCode = asyncHttpClient.prepareGet(\"http://www.example.com/\")\n        .execute(new AsyncHandler\u003cInteger\u003e () {\n            private Integer status;\n            \n            @Override\n            public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {\n                status = responseStatus.getStatusCode();\n                return State.ABORT;\n            }\n            \n            @Override\n            public State onHeadersReceived(HttpHeaders headers) throws Exception {\n              return State.ABORT;\n            }\n            \n            @Override\n            public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {\n                 return State.ABORT;\n            }\n        \n            @Override\n            public Integer onCompleted() throws Exception{\n                return status;\n            }\n        \n            @Override\n            public void onThrowable(Throwable t) {\n                t.printStackTrace();\n            }\n        });\n\n        Integer statusCode = whenStatusCode.get();\n```\n\n#### Using Continuations\n\n`ListenableFuture` has a `toCompletableFuture` method that returns a `CompletableFuture`.\nBeware that canceling this `CompletableFuture` won't properly cancel the ongoing request.\nThere's a very good chance we'll return a `CompletionStage` instead in the next release.\n\n```java\nCompletableFuture\u003cResponse\u003e whenResponse=asyncHttpClient\n        .prepareGet(\"http://www.example.com/\")\n        .execute()\n        .toCompletableFuture()\n        .exceptionally(t-\u003e{ /* Something wrong happened... */  })\n        .thenApply(response-\u003e{ /*  Do something with the Response */ return resp;});\n        whenResponse.join(); // wait for completion\n```\n\nYou may get the complete maven project for this simple demo\nfrom [org.asynchttpclient.example](https://github.com/AsyncHttpClient/async-http-client/tree/master/example/src/main/java/org/asynchttpclient/example)\n\n## WebSocket\n\nAsync Http Client also supports WebSocket.\nYou need to pass a `WebSocketUpgradeHandler` where you would register a `WebSocketListener`.\n\n```java\nWebSocket websocket = c.prepareGet(\"ws://demos.kaazing.com/echo\")\n        .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(\n                new WebSocketListener() {\n\n                  @Override\n                  public void onOpen(WebSocket websocket) {\n                    websocket.sendTextFrame(\"...\").sendTextFrame(\"...\");\n                  }\n\n                  @Override\n                  public void onClose(WebSocket websocket) {\n                    // ...\n                  }\n\n                  @Override\n                  public void onTextFrame(String payload, boolean finalFragment, int rsv) {\n                    System.out.println(payload);\n                  }\n\n                  @Override\n                  public void onError(Throwable t) {\n                    t.printStackTrace();\n                  }\n                }).build()).get();\n```\n\n## User Group\n\nKeep up to date on the library development by joining the Asynchronous HTTP Client discussion group\n\n[GitHub Discussions](https://github.com/AsyncHttpClient/async-http-client/discussions)\n","funding_links":[],"categories":["Java","Networking","Projects","Index","Libs","III. Network and Integration","常用框架\\\u0026第三方库","网络编程","项目","\u003ca name=\"Java\"\u003e\u003c/a\u003eJava"],"sub_categories":["HTTP Clients","Networking","\u003cA NAME=\"Network\"\u003e\u003c/A\u003eNetwork","2. Networking","HTTP客户端"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAsyncHttpClient%2Fasync-http-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAsyncHttpClient%2Fasync-http-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAsyncHttpClient%2Fasync-http-client/lists"}