回复
鸿蒙app访问网络和json解析(导入第三方依赖) 原创 精华
^浅忆佳瓦~苦思甜
发布于 2022-5-1 22:31
浏览
4收藏
1.网络请求结果如下:
2.新建项目,在ability_main.xml布局如下:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="top"
ohos:orientation="vertical">
<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text="网络数据访问"
ohos:text_size="40vp"
/>
<Button
ohos:id="$+id:btn1"
ohos:height="match_content"
ohos:width="match_parent"
ohos:text="访问api接口"
ohos:text_color="#ffffff"
ohos:text_size="30fp"
ohos:background_element="#ff0000"
ohos:top_margin="15vp"/>
<Text
ohos:id="$+id:result_text"
ohos:height="match_content"
ohos:width="match_content"
ohos:top_margin="30vp"
ohos:text="返回结果"
ohos:background_element="#21a8fd"
ohos:text_size="20fp"
ohos:multiple_lines="true"/>
</DirectionalLayout>
3.在配置文件config.json中添加访问网络的请求:
"reqPermissions": [
{
"name":"ohos.permission.GET_NETWORK_INFO"
},
{
"name":"ohos.permission.SET_NETWORK_INFO"
},
{
"name":"ohos.permission.INTERNET"
}
]
4.在这里封装一下网络请求的工具类,方便工程调用和复用,工具类封装如下:
public class HttpRequestUtil {
/**
* 有前三个参数即可访问成功,设置更多参数以便更通用
* @param context 上下文
* @param urlString 请求的接口路径
* @param requestMethod 请求方式:GET POST DELETE PUT
* @param token 访问受限资源携带token,非受限资源传递null即可
* @param data 当请求方式为PUT/POST时,通过请求体传递数据(JSON格式的字符串)
* @return 返回请求结果(字符串类型)
*/
private static String sendRequest(Context context,String urlString,String requestMethod,String token,String data){
String result = null;
//创建链接
NetManager netManager = NetManager.getInstance(context);
if (!netManager.hasDefaultNet()) {
return null;
}
NetHandle netHandle = netManager.getDefaultNet();
// 可以获取网络状态的变化
NetStatusCallback callback = new NetStatusCallback() {
// 重写需要获取的网络状态变化的override函数
};
netManager.addDefaultNetStatusCallback(callback);
// 通过openConnection来获取URLConnection
HttpURLConnection connection = null;
try {
//发送链接
URL url = new URL(urlString);
connection = (HttpURLConnection) netHandle.openConnection(url, Proxy.NO_PROXY);
//设置请求方式
connection.setRequestMethod(requestMethod);
if (data != null){
//允许通过此网络连接向服务器端写数据
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
}
//如果参数token!=null,则需要将token设置到请求头
if (token != null){
connection.setRequestProperty("token",token);
}
//发送请求建立连接
connection.connect();
//向服务器传递data中的数据
if (data != null){
byte[] bytes = data.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write(bytes);
os.flush();
}
//获取链接结果
//从连接中获取输入流,读取api接口返回的数据
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream is = connection.getInputStream();
StringBuilder builder = new StringBuilder();
byte[] bs = new byte[1024];
int len = -1;
while ((len = is.read(bs)) != -1){
builder.append(new String(bs,8,len));
}
result = builder.toString();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if (connection != null){
connection.disconnect();
}
}
return result;
}
//get请求
public static String sendGetRequest(Context context,String urlString){
return sendRequest(context,urlString,"GET",null,null);
}
public static String sendGetRequestWithToken(Context context,String urlString,String token){
return sendRequest(context,urlString,"GET",token,null);
}
//post请求
public static String sendPostRequest(Context context,String urlString){
return sendRequest(context,urlString,"POST",null,null);
}
public static String sendPostRequestWithToken(Context context,String urlString,String token){
return sendRequest(context,urlString,"POST",token,null);
}
public static String sendPostRequestWithData(Context context,String urlString,String data){
return sendRequest(context,urlString,"POST",null,data);
}
public static String sendPostRequestWithTakenWithData(Context context,String urlString,String token,String data){
return sendRequest(context,urlString,"POST", token,data);
}
}
5.在MainAbilitySlice.java文件中的onstart方法中(注意:访问网络要在子线程中完成):
Text text = findComponentById(ResourceTable.Id_result_text);
Button btn1 = findComponentById(ResourceTable.Id_btn1);
btn1.setClickedListener(component -> {
//如果在此进行网络访问,会报错(不能在主线程中进行网络访问)
//原因:移动应用中不允许在主线程中运行耗时的程序
//解决:将耗时的操作放在一个独立的线程中完成,主线程就不会被阻塞
//方法:创建TaskDispatcher对象
//参数TaskPriority:线程优先级,default表示默认
TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
//globalTaskDispatcher.syncDispatch();//同步线程分发,见官方文档
//globalTaskDispatcher.asyncDispatch();//异步线程分发
globalTaskDispatcher.asyncDispatch(() -> {
//访问网络接口
String urlString = "https://api.muxiaoguo.cn/api/Gushici";//此处为木小果免费接口
//将访问网络结构的代码放在工具类中,方便引用
result = HttpRequestUtil.sendGetRequest(this,urlString);
System.out.println("-------》》》访问网络接口返回的结果是:" + result);
});
});
6.接下来介绍一下如何引用第三方依赖(Gradle):
仓库的官方网址:仓库
6.1在搜索框搜索Gson,然后点击谷歌旗下的
6.2选择合适的版本,然后点击gradle(因为鸿蒙app开发使用的是gradle),复制如下的代码:
6.3然后在entry模块下的build.gradle文件下添加:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])
testImplementation 'junit:junit:4.13.1'
ohosTestImplementation 'com.huawei.ohos.testkit:runner:2.0.0.200'
// 导入Gson依赖
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9'
}
6.4此时便可以创建Gson对象了:
Gson gson = new Gson();
6.5主要调用这两个方法:
gson.fromJson(String,Class);
gson.toJson(Object);
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2022-5-1 22:31:21修改
赞
3
收藏 4
回复
相关推荐