[英]How to send Retrofit POST body as JSON String?
我有如下服务。 我将方法Retroifit
库。 当我发送带有@Body Test
类型的参数时,该服务有效,但我想使用@Body String
我不创建Test
class 并在@Body
中使用它。 我创建了一个JSONObject
并将其转换为String
但是这样,程序不起作用? 你能帮我或建议一个解决方案吗?
我的 Web API:
[Route("TestService"), HttpPost, IgnoreDataLog]
public async Task<Result<TestResult>> Add(Test pmDeviceObj)
{
var listResult = await pmService.AddAsync(pmDeviceObj);
return listResult;
}
Android 部分:
@POST("TestService")
Call<Result<TestResult>> TestService(@Header("Content-Type") String content_type,@Body String body);
在 Android 中调用服务-> 我使用以下代码获得 StatusCode 400
JSONObject jsonBody=new JSONObject();
try {
jsonBody.put("Id",73);
jsonBody.put("seri","55656573");
jsonBody.put("code","fc24009b9160");
jsonBody.put("sID",8);
}catch (JSONException ex){
ex.printStackTrace();
}
retrofit2.Call<Result<TestResult>> call1=service.TestService("application/json",jsonBody.toString());
如果我在 Android 部分中使用以下代码,则一切正常,我将获取数据。
@POST("TestService")
Call<Result<TestResult>> TestService(@Header("Content-Type") String content_type,@Body Test inputValue);
Test test=new Test(73,"556565","fc24009b9160",8);
retrofit2.Call<Result<TestResult>> call1=service.TestService("application/json",test);
This happens because Retrofit
considers String
as a 'normal' object that has to be converted to a JSON and is not aware that it already is a JSON represntation of object.
如果您配置了HttpLogginInterceptor
,您应该会看到(简化示例)您的 JSON 字符串:
{“sId”:“8”}
实际上是这样的:
"{\"sId\": \"8\"}"
为了防止这种情况发生,您需要使用评论中建议的ScalarsConverterFactory
。 首先,您需要为其设置依赖项:
适用于 Gradle
dependencies {
implementation “com.squareup.retrofit2:converter-scalars:2.4.0”
}
或用于 Maven
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-scalars</artifactId>
<version>2.4.0</version>
</dependency>
完成后,您需要将转换器工厂添加到您的 Retrofit 中,例如(还添加了日志以便于测试):
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(MY_URL)
// be sure to add this before gsonconverterfactory!
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory
.create())
.client(client).build();
myApi = retrofit.create(MY_API_CLASS);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.