鸿蒙网络请求(下):工具类封装和使用 原创

发布于 2021-8-5 16:08
浏览
3收藏

通过上一篇鸿蒙网络请求的教程,了解了网络请求的基本用法,这一篇文章主要是对上一篇鸿蒙网络请求代码的进一步封装,把网络请求封装成一个工具类。

1. 网络请求工具类 RequestUtil

package com.example.hmrequest.util;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class RequestUtil {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00202, "Network");

    public ZSONObject get(String requestUrl, Map<String, String> params) {
        HttpURLConnection connection = null;
        try {
            connection = getHttpURLConnection(appendParams(requestUrl, params),"GET");
            connection.connect();

            String response = RequestUtil.getReturnString(connection.getInputStream());
            ZSONObject zsonObject = ZSONObject.stringToZSON(response);
            HiLog.info(LABEL,"%{public}s", zsonObject);
            return zsonObject;

        } catch (Exception e) {
            HiLog.error(LABEL,"%{public}s", e.getMessage());
        }
        return null;
    }

     public ZSONObject post(String requestUrl, Map<String, String> params) {
        HttpURLConnection connection = null;
        try {
            connection = getHttpURLConnection(requestUrl,"POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.connect();

            String paramJson = ZSONObject.toZSONString(params);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(paramJson);
            writer.close();

            String response = RequestUtil.getReturnString(connection.getInputStream());
            ZSONObject zsonObject = ZSONObject.stringToZSON(response);
            HiLog.info(LABEL,"%{public}s", zsonObject);
            return zsonObject;

        } catch (Exception e) {
            HiLog.error(LABEL,"%{public}s", e.getMessage());
        }
        return null;
    }


    private HttpURLConnection getHttpURLConnection(String requestURL, String requestMethod) throws IOException {
        URL url = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10*1000);
        connection.setReadTimeout(15*1000);
        connection.setRequestMethod(requestMethod);
        return connection;
    }

    private static String getReturnString(InputStream is) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            String buf = sb.toString();
            return buf;
        } catch (Exception var5) {
            return null;
        }
    }

    private String appendParams(String path,Map<String, String> paramsMap) {
        if(paramsMap != null){
            path = path+"?";
            for (String key: paramsMap.keySet()){
                path = path + key+"="+paramsMap.get(key)+"&";
            }
            path = path.substring(0,path.length()-1);
        }
        return path;
    }
}

2. 如何使用RequestUtil

要在子线程中使用网络请求:

 @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
               // getRequest();
                postRequest();
            }
        });
        mThread.start();
    }

1、GET请求

private void getRequest() {

    String requestUrl = "https://sapi.k780.com";
    HashMap params = new HashMap();
    ZSONObject zsonObject = new RequestUtil().get(requestUrl, null);
    HiLog.info(LABEL,"%{public}s", zsonObject);
}

2、POST请求

private void postRequest() {

    String requestUrl = "https://blog.changshanhuoshan.cn/web/blog/list";
    HashMap params = new HashMap();
    params.put("pageNum", "1");
    params.put("pageSize", "10");
    ZSONObject zsonObject = new RequestUtil().post(requestUrl, params);
    HiLog.info(LABEL,"%{public}s", zsonObject);
}

源代码地址

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
HarmonyOS_Request.zip 1.48M 28次下载
2
收藏 3
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐