​
private JSONObject executeApi(JSONObject jsonObject, String method) throws Exception {
        OkHttpClient client = OkHttpClientUtil.getInstance();
        String auth = systemCode + "-" + username + ":" + password;
        String authorizationHeader = StringPool.BASIC + new String(Base64Utils.encode(auth.getBytes()), StandardCharsets.UTF_8);
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonObject.toString(), mediaType);

        Request request = new Request.Builder()
                .url("http://" + host + path + "&method=" + method)
                .addHeader(StringPool.AUTHORIZATION, authorizationHeader)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        if (response.isSuccessful() && response.body() != null) {
            return JSONObject.parseObject(response.body().string());
        }
        return new JSONObject();
    }

​

之前一直使用restTemplate请求,想换okhttp3试试,但接口一直返回“请求类型必须为“application/json”错误信息。
我试试body里设置导致下面Header没生效,没想到还真是。

private JSONObject executeApi(JSONObject jsonObject, String method) throws Exception {
        OkHttpClient client = OkHttpClientUtil.getInstance();
        String auth = systemCode + "-" + username + ":" + password;
        String authorizationHeader = StringPool.BASIC + new String(Base64Utils.encode(auth.getBytes()), StandardCharsets.UTF_8);
//        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonObject.toString(), null);

        Request request = new Request.Builder()
                .url("http://" + host + path + "&method=" + method)
                .addHeader(StringPool.AUTHORIZATION, authorizationHeader)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        if (response.isSuccessful() && response.body() != null) {
            return JSONObject.parseObject(response.body().string());
        }
        return new JSONObject();
    }

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐