赞
踩
本文介绍如何在鸿蒙中使用网络请求,获取服务器数据并进行处理。
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
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; } }
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; } }
public interface ApiService {
@GET("hspbc/harmonyos_demos/raw/master/networkDemo/data.json")
Call<Task> queryTask();
}
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<Task>() { @Override public void onResponse(Call<Task> call, Response<Task> 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<Task> call, Throwable throwable) { HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "网页访问异常"); } }); } }
https://gitee.com/hspbc/harmonyos_demos/tree/master/networkDemo
《零基础学安卓编程》
《零基础学Java编程》
《零基础学鸿蒙编程》
厦门大学计算机专业 | 前华为工程师
专注《零基础学编程系列》,包含:Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
全网可关注:花生皮编程
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。