2016-09-06 62 views
0

我正在使用Retrofit2.0用於製作GET請求我的REST URL。我不需要將任何參數傳遞給URL來提出請求。 怎麼可以做出這種類型的請求?如何使用Retrofit2.0製作Java REST API GET請求?

這是我的代碼,我做了什麼!

接口::

public interface AllRolesAPI { 
    @GET("/SportsApp/allroles") 
    Call<AllRolesParams> getAllRoles(); 
} 

類::: 我創造了用POJO庫它包含了所有與setter和getter方法變量的類。

public void requestRoles() { 
     Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(ENDPOINT) 
       .build(); 

     AllRolesAPI allRolesParams = retrofit.create(AllRolesAPI.class); 
     Call<AllRolesParams> allRolesParamsCall = allRolesParams.getAllRoles(); 
     allRolesParamsCall.enqueue(new Callback<AllRolesParams>() { 
      @Override 
      public void onResponse(Call<AllRolesParams> call, Response<AllRolesParams> response) { 
       //response.body().getErrDesc(); 
       Log.v("SignupActivity", "Response :: " + response.body().getErrDesc()); 
      } 

      @Override 
      public void onFailure(Call<AllRolesParams> call, Throwable t) { 
       Log.v("SignupActivity", "Failure :: "); 
      } 
     }); 
    } 

當我創建像上面我已經得到了在控制檯::這個錯誤的請求

java.lang.IllegalArgumentException: Unable to create converter for class com.acknotech.kiran.navigationdrawer.AllRolesParams. 

回答

1

如果你的API的響應是JSON,你需要添加

Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl(ENDPOINT) 
    .addConverterFactory(GsonConverterFactory.create()) 
    .build(); 

爲了爲了能夠使用GsonConverterFactory,您需要添加一個gradle依賴項。檢查this。你的情況是

compile 'com.squareup.retrofit2:converter-gson:2.1.0' 

(2.1.0是在寫這篇文章時的最新版本)

+0

當我改變你說的代碼...排隊顯示錯誤,就像找不到符號。 – Jaccs

+0

是的,因爲您需要將該依賴項添加到build.gradle文件中,並同步項目 –

+0

否..仍然出錯。 (); Retrofit retrofit = new Retrofit.Builder() .baseUrl(ENDPOINT) .addConverterFactory(GsonConverterFactory.create()) .build(); AllRolesAPI allRolesAPI = retrofit.create(AllRolesAPI.class); 調用 allrolesResponseCall = allRolesAPI.getAllRoles(); 這是什麼代碼現在我應該如何使得請求沒有任何參數傳遞。 – Jaccs

0

引述官方的文檔:

默認情況下,改造只能反序列化HTTP機構成OkHttp的 ResponseBody類型,它只能接受其請求體類型 @Body。可以添加轉換器來支持其他類型。爲了您的方便,六個兄弟 模塊適應流行的序列化庫。

GSON:com.squareup.retrofit2:轉換器-GSON
傑克遜:com.squareup.retrofit2:轉換器,傑克遜
莫希:com.squareup.retrofit2:轉換器-莫希
的Protobuf:com.squareup.retrofit2 :變換器的protobuf
絲:com.squareup.retrofit2:轉換器線
簡單的XML:com.squareup.retrofit2:轉換器-simplexml的 標量(原語,盒裝和String):com.squareup.retrofit2:轉換器 - 標量

您試圖在沒有任何轉換器的情況下解析JSON。有多種可用於改造的轉換器。最受歡迎的是來自Google的Gson Converter。爲了使你的代碼工作創造改造適配器是這樣的:

adapter = new Retrofit.Builder() //in your case replace adapter with Retrofit retrofit 
.baseUrl(BASE_URL) 
.addConverterFactory(GsonConverterFactory.create()) 
.build(); 

同時一定要包括這些依賴關係:

compile 'com.google.code.gson:gson:2.6.2'  
compile 'com.squareup.retrofit2:retrofit:2.1.0'  
compile 'com.squareup.retrofit2:converter-gson:2.1.0' 

希望它works.You可以參考official retrofit docsthis guidegson guide以獲取更多信息。