how to send JSONObject into retrofit API call android

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 12:01:28

问题


I have implemented first time retrofit in my android code and facing follwing issues

getting following error : java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #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;
}

}

Passing the value to 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);
                             }
                         }
            );

回答1:


You are using the Android internal Json APIs. You need to use Gson's classes instead.

Call<JsonObject> sendLocation(@Body JsonObject jsonObject);

Hence the import statement

import com.google.gson.JsonObject;

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);
   }
});


来源:https://stackoverflow.com/questions/42529732/how-to-send-jsonobject-into-retrofit-api-call-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!