为什么 Retrofit2 在我的 POST body 中添加引号?
Why is Retrofit2 adding quotes to my POST body?
我有一个 API 请求,其中 POST
body 是 hex-encoded 以纯文本形式传输的二进制数据。由于我无法辨别的原因,Retrofit2 在将 hex-encoded 字符串添加到请求之前在其周围添加引号,这会导致服务器阻塞并抱怨格式错误的请求。
我们正在将我们的应用程序从原始 Retrofit 转换为 Retrofit2,none 有效负载生成代码已完全更改。
我已经能够通过使用 Interceptor
在运行时从请求 body 中删除封闭引号来解决这个问题,但这似乎是一个非常愚蠢的箍必须跳过,我宁愿不让引号出现在第一位。
我的界面是这样的:
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body String hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
我已经尝试将 Content-Type
header 设置为各种值,但没有明显效果。我还没有构建自定义类型转换器,因为似乎没有必要为普通的旧字符串创建一个自定义类型转换器。
谁能告诉我哪里做错了?
双引号是合乎逻辑的,因为改造是以 json 格式发送数据,因此如果类型为 String 则使用双引号。试试这个它可能对你有帮助。
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body RequestBody hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
String strRequestBody = "body";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),strRequestBody);
更新,对于 Kotlin,Code_Life 代码应如下所示:
interface SampleApi {
@POST("sample-endpoint")
suspend fun postThing(
@Body presentation: RequestBody,
@Header(HttpHeaders.DATE) gmtDateStr: String,
@Header("X-CUSTOM-ONE") custom1: Long,
@Header("X-CUSTOM-TWO") custom2: String
): Call<ApiResponse>
}
val strRequestBody = "body"
val requestBody = strRequestBody.toRequestBody("text/plain".toMediaTypeOrNull()
我有一个 API 请求,其中 POST
body 是 hex-encoded 以纯文本形式传输的二进制数据。由于我无法辨别的原因,Retrofit2 在将 hex-encoded 字符串添加到请求之前在其周围添加引号,这会导致服务器阻塞并抱怨格式错误的请求。
我们正在将我们的应用程序从原始 Retrofit 转换为 Retrofit2,none 有效负载生成代码已完全更改。
我已经能够通过使用 Interceptor
在运行时从请求 body 中删除封闭引号来解决这个问题,但这似乎是一个非常愚蠢的箍必须跳过,我宁愿不让引号出现在第一位。
我的界面是这样的:
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body String hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
我已经尝试将 Content-Type
header 设置为各种值,但没有明显效果。我还没有构建自定义类型转换器,因为似乎没有必要为普通的旧字符串创建一个自定义类型转换器。
谁能告诉我哪里做错了?
双引号是合乎逻辑的,因为改造是以 json 格式发送数据,因此如果类型为 String 则使用双引号。试试这个它可能对你有帮助。
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body RequestBody hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
String strRequestBody = "body";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),strRequestBody);
更新,对于 Kotlin,Code_Life 代码应如下所示:
interface SampleApi {
@POST("sample-endpoint")
suspend fun postThing(
@Body presentation: RequestBody,
@Header(HttpHeaders.DATE) gmtDateStr: String,
@Header("X-CUSTOM-ONE") custom1: Long,
@Header("X-CUSTOM-TWO") custom2: String
): Call<ApiResponse>
}
val strRequestBody = "body"
val requestBody = strRequestBody.toRequestBody("text/plain".toMediaTypeOrNull()