本文介绍了如何将 JSONObject 发送到 Retrofit API 调用 Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我第一次在我的 Android 代码中实现了 Retrofit,但面临以下问题:
I have implemented the first time Retrofit in my Android code and am facing the following issues:
java.lang.IllegalArgumentException:@Body 参数不能与表单或多部分编码一起使用.(参数#1)
我已经实现了如下代码:
I have implemented my code like below:
public interface APIService {
@FormUrlEncoded
@POST("/")
@Headers({
"domecode: axys",
"Content-Type: application/json;charset=UTF-8"
})
Call<JsonObject> sendLocation(@Body JsonObject jsonObject);
}
public class ApiUtils {
static String tempUrl = "http://192.168.16.114:8092/api/v1/location/tsa/";
public static APIService getAPIService() {
return RetrofitClient.getClient(tempUrl).create(APIService.class);
}
}
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if(retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
将值传递给 API 调用
Passing the value to an API call
JsonObject postParam = new JsonObject();
try {
postParam.addProperty(Fields.ID, "asdf");
}
Call<JsonObject> call = apiService.sendLocation(postParam);
call.enqueue(
new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("response", "Getting response from server: " + response);
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("response", "Getting response from server: " + t);
}
}
);
推荐答案
您正在使用 Android 内部 JSON API.您需要改用 Gson 的类.
You are using the Android internal JSON APIs. You need to use Gson's classes instead.
Call<JsonObject> sendLocation(@Body JsonObject jsonObject);
因此导入语句
import com.google.gson.JsonObject;
另一个错误是将 Callback 作为参数传递给请求
Another error is passing the Callback as a parameter to the request
Call<JsonObject> call = apiService.sendLocation(jsonObject);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("response", "Getting response from server: "+response);
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("response", "Getting response from server: " + t);
}
});
这篇关于如何将 JSONObject 发送到 Retrofit API 调用 Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!