2016-09-06 79 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以获取更多信息。