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

如何用Scala Sttp Client下载AWS定价公开JSON文件?

解决Sttp Client下载AWS定价JSON时的UnsupportedEncodingException问题

问题原因

你设置的Accept: application/octet-stream请求头会导致AWS定价服务返回的响应缺少明确的编码标识,Sttp Client在尝试将响应体解析为字符串时无法识别正确编码,从而抛出UnsupportedEncodingException。而浏览器和Postman会自动处理编码推断,所以能正常下载。

解决方案

方案1:移除错误的Accept头,使用默认字符串解析

直接去掉Accept头设置,让请求默认接受JSON格式,Sttp会自动处理响应编码:

val request: Request[Either[String, String], Any] = basicRequest
    .get(uri"https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json")

val response = request.send(sttpBackend)
val res = Await.result(response, 30.seconds)

方案2:显式指定Accept为JSON,确保服务端返回正确编码

如果需要明确指定Accept头,设置为application/json:

import sttp.model.HeaderNames
import sttp.model.MediaType

val request: Request[Either[String, String], Any] = basicRequest
    .header(HeaderNames.Accept, MediaType.ApplicationJson.toString())
    .get(uri"https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json")

val response = request.send(sttpBackend)
val res = Await.result(response, 30.seconds)

方案3:直接获取字节数组手动解码

如果前两种方案仍有编码问题,可以直接获取响应字节数组,再用UTF-8手动解码:

import java.nio.charset.StandardCharsets

val request: Request[Either[String, Array[Byte]], Any] = basicRequest
    .get(uri"https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json")
    .response(asByteArray)

val response = request.send(sttpBackend)
val res = Await.result(response, 30.seconds)
val jsonString = res.map(bytes => new String(bytes, StandardCharsets.UTF_8))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:42:05