零基础学鸿蒙编程-网络请求

简要介绍

本文介绍如何在鸿蒙中使用网络请求,获取服务器数据并进行处理。

集成步骤

  1. entry工程的build.gradle中添加依赖
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
  1. 在config.json中添加权限
    "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  1. 添加数据类:Task.java
public class Task {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

  1. 添加网络接口管理类:ApiManager.java
public class ApiManager {
    private static final String BASE_URL = "https://gitee.com/";

    private static ApiService apiService;
    private static ApiManager instance = new ApiManager();

    private ApiManager() {
        apiService = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder().build())
                .build().create(ApiService.class);
    }

    public static ApiManager getInstance() {
        return instance;
    }

    public ApiService getApiService() {
        return apiService;
    }
}
  1. 添加网络接口调用类:ApiService.java
public interface ApiService {
    @GET("hspbc/harmonyos_demos/raw/master/networkDemo/data.json")
    Call queryTask();
}

  1. java代码中调用:MainAbilitySlice.java
public class MainAbilitySlice extends AbilitySlice {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        findComponentById(ResourceTable.Id_text).setClickedListener(component -> query());
    }

    private void query() {
        ApiManager.getInstance().getApiService().queryTask().enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (!response.isSuccessful() || response.body() == null) {
                    onFailure(null, null);
                    return;
                }
                Task result = response.body();
                new ToastDialog(getContext()).setText(result.getName()).show();
            }

            @Override
            public void onFailure(Call call, Throwable throwable) {
                HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "网页访问异常");
            }
        });
    }
}

效果图

零基础学鸿蒙编程-网络请求

完整源代码

https://gitee.com/hspbc/harmonyos_demos/tree/master/networkDemo

展开阅读全文

页面更新:2024-04-06

标签:鸿蒙   网络   简要   效果图   源代码   步骤   异常   接口   本文   基础   数据

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top