# ohosAsync **Repository Path**: HarmonyOS-tpc/ohosAsync ## Basic Information - **Project Name**: ohosAsync - **Description**: OHosAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Ohos aware, http request library, check out Ion (it is built on top of OhosAsync) - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 2 - **Created**: 2021-04-01 - **Last Updated**: 2024-05-29 ## Categories & Tags **Categories**: harmonyos-network **Tags**: None ## README # OhosAsync_HarmonyOS OHosAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Ohos aware, http request library, check out Ion (it is built on top of OhosAsync). The typical Ohos app developer would probably be more interested in Ion. But if you're looking for a raw Socket, HTTP(s) client/server, and WebSocket library for Ohos, OhosAsync is it. Features Based on NIO. Single threaded and callback driven. All operations return a Future that can be cancelled Socket client + socket server HTTP client + server WebSocket client + server ## 集成配置 ### 方法一: ``` 通过library生成har包,添加har包到libs文件夹内 在entry的gradle内添加如下代码 implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) ``` ### 方法二: ``` allprojects{ repositories{ mavenCentral() } } implementation 'io.openharmony.tpc.thirdlib:OhosAsyncLibrary:1.0.4' ``` ## 功能介绍如下: ### Download a url to a String ```java Uri parse = Uri.parse("https://httpbin.org/get"); AsyncHttpRequest get = new AsyncHttpRequest(parse, "GET"); AsyncHttpClient.getDefaultInstance().executeString(get, new AsyncHttpClient.StringCallback() { @Override public void onCompleted(Exception e, AsyncHttpResponse source, String result) { LogUtil.info(LOGTAG, result); } }); ``` ### Download JSON from a url ```java Uri parse = Uri.parse("https://xxxxxxxxxxxx"); AsyncHttpRequest get = new AsyncHttpRequest(parse, "GET"); AsyncHttpClient.getDefaultInstance().executeJSONObject(get, new AsyncHttpClient.JSONObjectCallback() { @Override public void onCompleted(Exception e, AsyncHttpResponse source, JSONObject result) { LogUtil.info(LOGTAG, result.toString()); } }); ``` ##### *Or for JSONArrays... ```java Uri parse = Uri.parse("https://xxxxxxxxxxxx"); AsyncHttpRequest get = new AsyncHttpRequest(parse, "GET"); AsyncHttpClient.getDefaultInstance().executeJSONArray(get, new AsyncHttpClient.JSONArrayCallback() { @Override public void onCompleted(Exception e, AsyncHttpResponse source, JSONArray result) { LogUtil.info(LOGTAG, result.toString()); } }); ``` ### Download a url to a file ```java AsyncHttpClient.getDefaultInstance().executeFile(new AsyncHttpGet(url), filename, new AsyncHttpClient.FileCallback() { @Override public void onCompleted(Exception e, AsyncHttpResponse response, File result) { if (e != null) { e.printStackTrace(); return; } } }); ``` #### Caching is supported too ```java try { ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(), FileUtils.createCach(getContext()), 1024 * 1024 * 10); } catch (IOException e) { e.printStackTrace(); } ``` ### Need to do multipart/form-data uploads? That works too ```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); } }); ``` ### Can also create web sockets ```java AsyncHttpClient.getDefaultInstance().websocket("get", "my-protocol", new AsyncHttpClient.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 WebSocket.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(); } }); } }); ``` ### OhosAsync also let's you create simple HTTP servers ```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!!! ``` ### And WebSocket Servers ```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!"); ``` ## Licenses ``` Copyright 2013 Koushik Dutta (2013) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### End