更新升级 专属应用 系统故障 硬件故障 电脑汽车 鸿蒙刷机 鸿蒙开发Linux教程 鸿蒙开发Linux命令
当前位置:HMXT之家 > 应用开发 > HarmonyOS鸿蒙应用能访问webapi接口吗

HarmonyOS鸿蒙应用能访问webapi接口吗

更新时间:2022-01-07 10:23:27浏览次数:125+次

HarmonyOS鸿蒙应用能访问webapi接口吗?

解答

1、可以的,能发起http请求就可以。不过有网友也认为需要使用HTTPS协议。

2、不管是想Java上访问Web API还是JS访问Web API,其实都是可以的。

3、import http from '@ohos.net.http';

\

4、Js请求Web Api接口可参考鸿蒙官方上的文档,Java请求Web Api代码如下所示:

public class NetworkManager {

    private static final String TAG = "hm_NetUtil";

    private static final String REQUEST_METHOD_GET = "GET";

    private static final String REQUEST_METHOD_POST = "POST";

    private static final String CACHE_PATH = "NetworkCache";

    private static NetworkManager instance;

    private Context context;

    private TaskDispatcher globalTaskDispatcher;

    private HttpResponseCache httpResponseCache;

    private int cacheValidTime = 60 * 60 * 24;

    private int connectTimeout = 10 * 1000;

    private int readTimeout = 10 * 1000;

    /**

     * constructor of NetworkManager

     *

     * @param context context

     */

    private NetworkManager(Context context) {

        this.context = context;

        globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);

        httpResponseCache = HttpResponseCache.getInstalled();

    }

    /**

     * getInstance of NetworkManager

     *

     * @param context context

     * @return NetworkManager

     */

    public static NetworkManager getInstance(Context context) {

        if (instance == null) {

            instance = new NetworkManager(context.getApplicationContext());

        }

        return instance;

    }

    /**

     * set connect time out and read time out

     *

     * @param connectTimeout connectTimeout

     * @param readTimeout    readTimeout

     */

    public void setTimeout(int connectTimeout, int readTimeout) {

        this.connectTimeout = connectTimeout;

        this.readTimeout = readTimeout;

    }

    /**

     * set cache valid time

     *

     * @param time time

     */

    public void setCacheValidTime(int time) {

        cacheValidTime = time;

    }

    /**

     * set cache size

     *

     * @param size size

     */

    public void setCacheSize(long size) {

        File httpCacheDir = new File(context.getCacheDir(), CACHE_PATH);

        try {

            HttpResponseCache.install(httpCacheDir, size);

        } catch (IOException e) {

            LogUtil.error(TAG, e.getMessage());

        }

    }

    /**

     * add FlowStatistics Callback

     *

     * @param callback callback

     */

    public void addFlowStatisticsCallback(FlowStatisticsCallback callback) {

        String packageName = context.getBundleName();

        IBundleManager iBundleManager = context.getBundleManager();

        int myUid = 0;

        try {

            BundleInfo bundleInfoundleInfo = iBundleManager.getBundleInfo(packageName, 0);

            myUid = bundleInfoundleInfo.uid;

        } catch (RemoteException e) {

            LogUtil.info(TAG, e.getMessage());

        }

        if (myUid != 0) {

            long rx1 = DataFlowStatistics.getUidRxBytes(myUid);

            long tx1 = DataFlowStatistics.getUidTxBytes(myUid);

            int finalMyUid = myUid;

            context.getGlobalTaskDispatcher(TaskPriority.DEFAULT)

                    .delayDispatch(

                            () -> {

                                long rx2 = DataFlowStatistics.getUidRxBytes(finalMyUid) - rx1;

                                long tx2 = DataFlowStatistics.getUidTxBytes(finalMyUid) - tx1;

                                context.getUITaskDispatcher()

                                        .asyncDispatch(

                                                () -> {

                                                    if (callback != null) {

                                                        callback.getFlowStatistics(tx2, rx2);

                                                    }

                                                });

                            },

                            1000);

        }

    }

    /**

     * 链接网络,获取数据

     *

     * @param strUrl   请求链接

     * @param callback 结果回调

     */

    public void requestGet(String strUrl, ResponseCallback callback) {

        globalTaskDispatcher.asyncDispatch(() -> {

            HttpURLConnection connection = null;

            try {

                connection = getNetConnection(strUrl, REQUEST_METHOD_GET);

                StringBuilder resultBuffer = new StringBuilder();

                int reqCode = connection.getResponseCode();

                if (reqCode == HttpURLConnection.HTTP_OK) {

                    InputStream dataStream = connection.getInputStream();

                    InputStreamReader inputStreamReader = new InputStreamReader(dataStream);

                    BufferedReader reader = new BufferedReader(inputStreamReader);

                    String tempLine;

                    while ((tempLine = reader.readLine()) != null) {

                        resultBuffer.append(tempLine);

                    }

                    if (callback != null) {

                        callback.onSuccess(resultBuffer.toString());

                    }

                    reader.close();

                    inputStreamReader.close();

                    if (dataStream != null) {

                        dataStream.close();

                    }

                    if (httpResponseCache != null) {

                        httpResponseCache.flush();

                    }

                } else {

                    throw new IOException(connection.getResponseMessage());

                }

            } catch (Exception e) {

                if (callback != null) {

                    callback.onFail(e.getMessage());

                }

            } finally {

                if (connection != null) {

                    connection.disconnect();

                }

            }

        });

    }

    /**

     * 链接网络,获取数据

     *

     * @param strUrl   请求链接

     * @param json     信息

     * @param callback callback

     */

    public void requestPost(String strUrl, String json, ResponseCallback callback) {

        globalTaskDispatcher.asyncDispatch(

                new Runnable() {

                    @Override

                    public void run() {

                        HttpURLConnection connection = null;

                        try {

                            connection = getNetConnection(strUrl, REQUEST_METHOD_POST);

                            InputStream dataStream;

                            StringBuilder resultBuffer = new StringBuilder();

                            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

                            out.write(json.getBytes(), 0, json.length());

                            int reqCode = connection.getResponseCode();

                            if (reqCode == HttpURLConnection.HTTP_OK) {

                                dataStream = connection.getInputStream();

                                InputStreamReader inputStreamReader = new InputStreamReader(dataStream);

                                BufferedReader reader = new BufferedReader(inputStreamReader);

                                String tempLine;

                                while ((tempLine = reader.readLine()) != null) {

                                    resultBuffer.append(tempLine);

                                }

                                if (callback != null) {

                                    callback.onSuccess(resultBuffer.toString());

                                }

                                reader.close();

                                inputStreamReader.close();

                                if (dataStream != null) {

                                    dataStream.close();

                                }

                                if (httpResponseCache != null) {

                                    httpResponseCache.flush();

                                }

                            } else {

                                throw new Exception(connection.getResponseMessage());

                            }

                        } catch (Exception e) {

                            if (callback != null) {

                                callback.onFail(e.getMessage());

                            }

                        } finally {

                            if (connection != null) {

                                connection.disconnect();

                            }

                        }

                    }

                });

    }

    /**

     * 链接网络,获取数据

     *

     * @param host     host

     * @param port     port

     * @param content  content

     * @param callback callback

     */

    public void requestSocket(String host, int port, String content, ResponseCallback callback) {

        NetManager netManager = NetManager.getInstance(context);

        NetHandle netHandle = netManager.getDefaultNet();

        if (netHandle == null) {

            return;

        }

        globalTaskDispatcher.asyncDispatch(

                new Runnable() {

                    @Override

                    public void run() {

                        DatagramSocket socket = null;

                        try {

                            InetAddress address = netHandle.getByName(host);

                            socket = new DatagramSocket(port);

                            netHandle.bindSocket(socket);

                            byte[] sendByte = content.getBytes();

                            DatagramPacket sendDp = new DatagramPacket(sendByte, sendByte.length, address, port);

                            socket.send(sendDp);

                            context.getUITaskDispatcher()

                                    .asyncDispatch(

                                            () -> {

                                                if (callback != null) {

                                                    callback.onSuccess(sendDp.toString());

                                                }

                                            });

                        } catch (IOException e) {

                            if (callback != null) {

                                callback.onFail(e.getMessage());

                            }

                            LogUtil.error(TAG, e.getMessage());

                        } finally {

                            if (socket != null) {

                                socket.close();

                            }

                        }

                    }

                });

    }

    /**

     * 获取Connection

     *

     * @param strUrl 请求链接

     * @param method 请求方式

     * @return HttpURLConnection对象

     * @throws Exception e

     */

    private HttpURLConnection getNetConnection(String strUrl, String method) throws Exception {

        NetManager netManager = NetManager.getInstance(context);

        NetHandle netHandle = netManager.getDefaultNet();

        if (netHandle == null) {

            throw new NullPointerException();

        }

        HttpURLConnection connection;

        SSLContext sslcontext = SSLContext.getInstance("TLS");

        sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());

        HostnameVerifier ignoreHostnameVerifier = (s, sslsession) -> true;

        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);

        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());

        URL url = new URL(strUrl);

        URLConnection urlConnection = netHandle.openConnection(url, java.net.Proxy.NO_PROXY);

        if (urlConnection instanceof HttpsURLConnection) {

            connection = (HttpsURLConnection) urlConnection;

        } else if (urlConnection instanceof HttpURLConnection) {

            connection = (HttpURLConnection) urlConnection;

        } else {

            throw new NullPointerException();

        }

        connection.setRequestMethod(method);

        connection.setConnectTimeout(connectTimeout);

        connection.setReadTimeout(readTimeout);

        connection.setDoOutput(true);

        connection.setDoInput(true);

        connection.addRequestProperty("Cache-Control", "max-age=0");

        connection.addRequestProperty("Cache-Control", "max-stale=" + cacheValidTime);

        connection.connect();

        return connection;

    }

}