2017-03-01 28 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

相關問題