调用成功时响应体为null(android)

时间:2016-05-05 02:14:18

标签: android asp.net-web-api retrofit2

请帮忙。我从android调用服务器上的方法,我得到了null响应体的成功。我的服务器是ASP.NET Web API,在Android客户端我使用retrofit2。

服务器上的方法(路由是“Players / IsParticipant /”):

        [AllowAnonymous]
    [Route("IsParticipant"), HttpGet]
    public IHttpActionResult IsParticipant(int meetingId, string username)
    {
        return Ok(true);
    }

在android中:

@GET("players/isParticipant")
Call<Boolean> isParticipant(@Query("username") String username, @Query("meetingId") int meetingId);

当我调用它时:

Call<Boolean> call = service.isParticipant("aa", 1);
    call.enqueue(new CustomCallback<Boolean>(this)
    {

        @Override
        public void onSuccess(Boolean model)
        {
            DialogUtils.Show(getApplicationContext(), model.toString());
        }
    });

我收到错误,因为模型为空。为什么?我该怎么办呢?我很感激任何建议。

1 个答案:

答案 0 :(得分:1)

您可以参考以下示例代码:

ASP.NET Web API:

[Route("api/values/getbool/{id:int}/{username}")]
public IHttpActionResult GetBool(int id, string username)
{
    return Ok(true);
}

机器人:

build.gradle文件:

dependencies {
    ...
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:converter-scalars:2.0.2'
    ...
}

WebAPIService.java:

public interface WebAPIService {
    ...
    @GET("/api/values/getbool/{id}/{username}")
    Call<Boolean> getBool(@Path("id") int id, @Path("username") String username);
    ...
}

MainActivity.java:

...
Retrofit retrofit1 = new Retrofit.Builder()
        .baseUrl(API_URL_BASE)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
WebAPIService service1 = retrofit1.create(WebAPIService.class);

Call<Boolean> booleanCall = service1.getBool(1, "user");
booleanCall.enqueue(new Callback<Boolean>() {
    @Override
    public void onResponse(Call<Boolean> call, Response<Boolean> response) {
        Log.i("onResponse", String.valueOf(response.body()));
    }

    @Override
    public void onFailure(Call<Boolean> call, Throwable t) {
        Log.e("onFailure", t.toString());
    }
});
...

Logcat结果:

05-05 14:10:30.291 15755-15755/com.example.asyncretrofit I/onResponse: true