我使用Retrofit 2库,我需要像这样发送POST JSON请求:
{
"datetime": 0,
"body": {
"gymId": "17C1B14C-C21F-41EE-BF75-F0E7843DB638",
"customerName": "test",
"customerEmail": "test@test.ru",
"content": "test"
}
}
我如何使用RequestBody发送此请求?
Call<ApiClubRequest> clubContact(@Body RequestBody requestBody);
或者可以轻易提出这样的要求?
这是我的OkHttp设置的接口类。
public class RestClient {
private static ClassApiInterface WordClassApiInterface ;
private static String baseUrl = "http://my adddress" ;
public static WorldClassApiInterface getClient() {
if (WordClassApiInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface = client.create(ApiInterface.class);
}
return ClassApiInterface ;
}
public static Call<ApiClubRequest> clubcontact(String gymId, String customerName, String
customerEmail, String content){
ClubContactRequest request = new ClubContactRequest();
request.gymId = gymId;
request.customerName = customerName;
request.customerEmail = customerEmail;
request.content = content;
return ApiInterface.clubContact(request);
}
@Headers("Content-Type: application/json")
@POST("/hotline")
Call<ApiClubRequest> clubContact(@Body ClubContactRequest requestBody);
} }
答案 0 :(得分:1)
创建一个请求类并创建与JSON中名称相同的字段:
public class ClubContactRequest {
public String gymId;
public String customerName;
public String customerEmail;
public String content;
}
修改POST @Body:
Call<ApiClubRequest> clubContact(@Body ClubContactRequest requestBody);
然后实施请求:
public Call<ApiClubRequest> clubcontact(String gymId, String customerName, String customerEmail, String content){
ClubContactRequest request = new ClubContactRequest();
request.gymId = gymId;
request.customerName = customerName;
request.customerEmail = customerEmail;
request.content = content;
return yourApiInterface.clubContact(request);
}