HarmonyOS应用开发-OkHttp3.0的使用

发布于 2021-12-24 10:16
浏览
2收藏

HarmonyOS应用开发-OkHttp3.0的使用

1.在build.gradle下引入OkHttp3.0:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    api 'com.squareup.okhttp3:okhttp:3.10.0'
}

2.配置网路访问权限与免加密访问:

"reqPermissions": [
  {"name":"ohos.permission.GET_NETWORK_INFO"},
  {"name":"ohos.permission.SET_NETWORK_INFO"},
  {"name":"ohos.permission.INTERNET"}
]

"deviceConfig": {
  "default": {
    "keepAlive": true,
    "network": {
      "cleartextTraffic": true
    }
  }
}

3.进行数据访问
Get:

String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
        .url(url)
        .get()//默认就是GET请求,可以不写
        .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d(TAG, "onFailure: ");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, "onResponse: " + response.body().string());
    }
});

Post:

MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
String requestBody = "I am Jdqm.";
Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(mediaType, requestBody))
        .build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d(TAG, "onFailure: " + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
        Headers headers = response.headers();
        for (int i = 0; i < headers.size(); i++) {
            Log.d(TAG, headers.name(i) + ":" + headers.value(i));
        }
        Log.d(TAG, "onResponse: " + response.body().string());
    }
});

标签
HarmonyOS应用开发-OkHttp3.0的使用.docx 15.8K 8次下载
2
收藏 2
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐