如何将JSONObject发送到改造API调用android

时间:2017-03-01 10:50:53

标签: android api retrofit retrofit2

  

我已经在我的Android代码中实现了第一次改造并面临以下问题

     

出现以下错误:java.lang.IllegalArgumentException:@Body参数不能与表单或多部分编码一起使用。 (参数#1)

我已经实现了我的代码,如下所示

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调用

           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 个答案:

答案 0 :(得分:11)

您正在使用Android内部Json API。你需要使用Gson的课程。

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

因此导入声明

import com.google.gson.JsonObject;

另一个错误是将Callback作为参数传递给请求

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