Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Get raw HTTP response with Retrofit

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

@POST("/login")
@FormUrlEncoded
Call<retrofit.Response> login(@Field("username") String login, @Field("password") String pass,
                     @Field("appName") String appName, @Field("appKey") String appKey);

But I get:

java.lang.IllegalArgumentException: Unable to create call adapter for retrofit.Call for method Api.login

I create Retrofit this way:

Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
retrofitBuilder.addConverterFactory(JacksonConverterFactory.create());
Retrofit retrofitAdapter = retrofitBuilder.baseUrl(baseUrl).build();
return retrofitAdapter.create(apiClass);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Call<ResponseBody> 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<ResponseBody> myCall = myApi.login(...)
myCall.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> 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<ResponseBody> response = myCall.execute();
System.out.println("response code" + response.code());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...