Get raw HTTP response with Retrofit

前端 未结 3 1590
有刺的猬
有刺的猬 2020-12-01 06:15

I want to get the raw http response from my API REST. I have tried with this interface:

@POST(\"/login\")
@FormUrlEncoded
Call login         


        
3条回答
  •  眼角桃花
    2020-12-01 06:25

    To get access to the raw response, use ResponseBody from okhttp as your call type.

    Call login(...)
    

    In your callback, you can check the response code with the code method of the response. This applies to any retrofit 2 return type, because your callback always gets a Response parameterized with your actual return type. For asynchronous --

    Call myCall = myApi.login(...)
    myCall.enqueue(new Callback() {
        @Override
        public void onResponse(Response response, Retrofit retrofit) {
            // access response code with response.code()
            // access string of the response with response.body().string()
        }
    
        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    });
    

    for synchronous calls --

    Response response = myCall.execute();
    System.out.println("response code" + response.code());
    

提交回复
热议问题