文档开发者中心
我的

鸿蒙应用能访问webapi接口吗

鸿蒙应用能访问webapi接口吗?
点赞
收藏
回复
6
分享
举报
浏览828 发布于2021-12-27 03:50未知归属地
全部评论
最多点赞
最新发布
最早发布

楼主你好,Js请求Web Api接口参考楼上的官方文档:https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-net-http-0000001168304341,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;
    }
}

展开全部
6楼回复于2021-12-28 02:17 未知归属地
需要使用HTTPS 协议
5楼回复于2021-12-27 13:52 未知归属地
请问你是想Java上访问Web API, 还是JS访问Web API 都是可以的。
4楼回复于2021-12-27 09:29 未知归属地

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

https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-net-http-0000001168304341

3楼回复于2021-12-27 07:25 未知归属地
可以的,能发起 http请求就可以
2楼回复于2021-12-27 04:55 未知归属地
欢迎开发小伙伴们进来帮帮楼主
1楼回复于2021-12-27 03:59 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要发帖子

了解社区公约,与您携手共创和谐专业的开发者社区。