鸿蒙okHttpClient网络请求 json格式参数

json格式请求接口--------------------------------------------------------------
public void loadData(String httpUrl,JsonObject jsonString,  BaseUrlCallback baseUrlCallback) {

    HiLog.info(LABEL_LOG, "请求接口=========="+ httpUrl);
    HiLog.info(LABEL_LOG,httpUrl+"参数=========="+ jsonString.toString());
    RequestBody requestBody = RequestBody.create(mediaType, jsonString.toString());
    Request requestPost = new Request.Builder()
            .url(httpUrl)
            .post(requestBody)
            .build();

    Call call = okHttpClient.newCall(requestPost);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //ToastDialog只能在主线程执行,所以获取主线程供子线程中创建ToastDialog,下同
            getMainTaskDispatcher().syncDispatch(() ->
                    new ToastDialog(BaseAbSlice.this)
                            .setText("请求失败,请检查网络连接是否正常")
                            .show());
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
                  if (response.body() != null) {
                    String result = response.body().string();
                     HiLog.info(LABEL_LOG, httpUrl+"返回的结果=========="+result);
                    JSONObject jsonObject = JSONObject.parseObject(result);

                   baseUrlCallback.onSuccess(jsonObject,httpUrl);

           }

         }

调用方法
JsonObject jsonString=new JsonObject();
jsonString.addProperty("meetingId", mettingListBean.getData());
loadData(这里写url,jsonString,this);

-------------------------------------------------------------------------------------------

用到的初始化信息

MediaType mediaType=MediaType.parse("application/json; charset=utf-8");;
OkHttpClient okHttpClient=new OkHttpClient();;;//网络访问请求对象
JsonObject jsonString=new JsonObject();
Gson gson = new GsonBuilder()
        .serializeNulls()
        .create();

——----------------------------------------------------------------------------------------------

 //回调子定义接口()

package xxxxxxxxxxxxxx写自己的包名;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.Response;

import java.io.IOException;

public interface BaseUrlCallback {
    void onError(IOException var2);

    void onSuccess(JSONObject jsonObject, String url) throws IOException;
}

你可能感兴趣的:(harmonyos,json,java)