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

长沙火山
发布于 2021-8-5 16:08
1.2w浏览
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;
    }
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.

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.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

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);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

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);
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

源代码地址

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
HarmonyOS_Request.zip 1.48M 46次下载
2
收藏 3
回复
举报
2
1
3
1条回复
按时间正序
/
按时间倒序
愿世界美好环环相扣
愿世界美好环环相扣

zsonObject是什么格式啊

回复
2022-4-15 09:30:48


回复
    相关推荐