Exception Handling In Android from Web API

 ̄綄美尐妖づ 提交于 2019-12-08 11:44:51

问题


My code in MVC API C# this:

    [System.Web.Http.HttpPost]
    [System.Web.Http.Route("api/ServiceV1/Test")]
    public IHttpActionResult Test()
    {
        return BadRequest("Catch this message in Android application");
    }

Result in PostMan

{
    "Message": "Catch this message in Android application"
}

I catch this error message on android application. I used okhttp3.

    String MIME_JSON = "application/json";
    Gson gson = new Gson();
    RequestBody body = RequestBody.create(MediaType.parse(MIME_JSON), gson.toJson(object));

    Request request = new Request.Builder()
            .url(baseUrl + route)
            .post(body)
            .build();

    okHttpClient.newCall(request).execute();

How do to catch this message on the Android application?


回答1:


the Call.execute() method returns a Response object, which has the code() method to find the status code, and the isSuccessful() method to find whether the code is in the [200,300) range, which generally represent success.

Generally looking at the documentation of libraries you are working with is helpful. Here's the documentation for okhttp




回答2:


Can read this error:

Response response=okHttpClient.newCall(request).execute();
if (response.code() != 200) {
  errorMessage= response.body().string();
}


来源:https://stackoverflow.com/questions/48484318/exception-handling-in-android-from-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!