2017-03-01 29 views
0

我已经实现了我的Android代码第一次改造和面向follwing问题如何发送的JSONObject到改造API调用的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); 
          } 
         } 
      ); 
+0

不要给回调'apiService.sendLocation(jsonObject.enqueue (new callback (){...});'。 –

回答

2

您正在使用Android内部的Json API。您需要改用Gson的类。

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

因此,import语句

import com.google.gson.JsonObject; 

另一个错误是经过回调作为参数来请求

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

java.lang.IllegalArgumentException:@Body参数不能与表单或多部分编码一起使用(参数#1) ed import com.google.gson.JsonObject;并更改并交叉检查,但得到相同的错误: – user1742971

+0

您需要将'JSONObject'更改为'JsonObject' –

+0

请检查我的更新代码: JsonObject postParam = new JsonObject(); 尝试postParam.addProperty(Fields.ID,“asdf”) postParam.addProperty(Fields._ID_OLD,“asdf”); postParam.addProperty(Fields.LATI,“asdf”); postParam.addProperty(Fields.LON,“asdf”) postParam.addProperty(Fields.OR_IDS,“asdf”); catch(JsonIOException e){ Log.d(TAG,e.getMessage()); } – user1742971

相关问题