使用 Retrofit 2 发送各种参数 (JSON) [英] Sending various parameters (JSON) using Retrofit 2
问题描述
这是接口方法:
@FormUrlEncoded
@POST ("url/myurl")
Call<JsonArray> sendParameters (@Header("x-imei") String imei, @Header("x-id-cliente") String idCliente, @Field("param1") JsonObject param1, @Field("param2") JsonArray param2, @Field("param3") JsonArray param3, @Field("param4") JsonArray param4,@Field("param5") JsonArray param5);
以及使用方法:
Call<JsonArray> peticion= RetrofitClient.getRetrofitClient(getActivity()).sendParameters(settings.getString("imei", ""), settings.getString("idCliente", ""),param1,param2,param3,param4,param5);
这样,电话就打不通了.
This way, the call is not working.
我尝试将所有接口参数更改为 String,并在调用中执行 param1.toString()、param2.toString() 等,但都不起作用.
I tried changing all the interface parameters to String, and doing param1.toString(), param2.toString() and so on in the call, and is not working neither.
是否有使用 Retrofit 2 在 POST 中发送 JsonObjects 和 JsonArrays 的简单方法?
Is there a simple way to send JsonObjects and JsonArrays in a POST, using Retrofit 2?
谢谢.
推荐答案
首先,您可以创建一个自定义类,并将其作为 POST 正文传递
First you can create a custom class which you want to pass as a POST body
class CustomClass {
String param1;
String parma2;
String param3;
//all of your params with getters and setters
}
然后根据带有 @Body 注释的新 CustomClass 实例更改 Retrofit 方法:
Then you change the Retrofit method according to your new CustomClass instance with the @Body annotation:
@POST ("url/myurl")
Call<JsonArray> sendParameters (@Header("x-imei") String imei, @Header("x-id-cliente") String idCliente, @Body CustomClass customClassInstance);
最终你调用发布数据:
CustomClass customClassInstance = new CustomClass();
customClassInstance.setParam1(...);
//...and so on
Call<JsonArray> peticion= RetrofitClient.getRetrofitClient(getActivity()).sendParameters(settings.getString("imei", ""), settings.getString("idCliente", ""), customClassInstance);
删除了 @FormUrlEncoded 注释
removed the @FormUrlEncoded annotation
这篇关于使用 Retrofit 2 发送各种参数 (JSON)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!