You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OkHttp首次调用execute方法返回乱码,后续调用正常求助

SharePoint接口首次调用返回乱码的解决方案

问题回顾

首次调用SharePoint接口时返回带乱码的内容:

▼♦

??{"value":[]}??☺??B?@D

后续调用可正常返回{"value":[]},Postman请求全程正常,使用OkHttp发起请求。

解决方案

  • 强制处理Gzip压缩响应
    SharePoint首次请求可能返回压缩后的内容,尽管OkHttp默认支持Gzip,但显式添加拦截器可确保压缩解码逻辑生效:

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(chain -> {
            Request compressedRequest = chain.request().newBuilder()
                .header("Accept-Encoding", "gzip, deflate")
                .build();
            Response response = chain.proceed(compressedRequest);
            // 确保响应头标记压缩类型,让OkHttp自动解码
            return response.body() != null && !response.headers().contains("Content-Encoding")
                ? response.newBuilder().header("Content-Encoding", "gzip").build()
                : response;
        })
        .build();
    
  • 移除Accept头中的streaming=true参数
    streaming=true可能触发SharePoint流式响应逻辑,导致首次请求编码异常,Postman会自动适配这类场景,修改请求头:

    .header("Accept", "application/json;odata=nometadata;charset=utf-8")
    
  • 显式指定UTF-8字符集解析响应
    避免OkHttp自动识别字符集错误,手动指定UTF-8解码响应体:

    if (responseBody != null) {
        responseString = responseBody.string(Charset.forName("UTF-8"));
    }
    
  • 清理OkHttp连接池
    首次连接可能存在异常缓存,请求完成后清理连接池避免复用异常连接:

    okHttpClient.connectionPool().evictAll();
    

验证建议

逐个测试上述方案,优先尝试移除streaming=true和显式指定字符集,这两个操作改动最小且针对性强。

内容的提问来源于stack exchange,提问作者hnnssy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:38:11