使用Retrofit获取原始HTTP响应 [英] Get raw HTTP response with Retrofit
问题描述
我想从我的API REST获取原始http响应。我试过这个界面:
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);
但我得到:
java.lang.IllegalArgumentException:无法为
retrofit.Call
为方法Api.login创建调用适配器
java.lang.IllegalArgumentException: Unable to create call adapter for retrofit.Call for method Api.login
我以这种方式创建 Retrofit
:
Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
retrofitBuilder.addConverterFactory(JacksonConverterFactory.create());
Retrofit retrofitAdapter = retrofitBuilder.baseUrl(baseUrl).build();
return retrofitAdapter.create(apiClass);
推荐答案
要访问原始响应,请使用<$来自okhttp的c $ c> ResponseBody 作为您的通话类型。
To get access to the raw response, use ResponseBody
from okhttp as your call type.
Call<ResponseBody> login(...)
在回调中,您可以使用<$ c检查响应代码$ c>代码响应方法。这适用于任何改装2返回类型,因为您的回调总是获得一个响应
参数化您的实际返回类型。对于异步 -
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();
}
});
用于同步通话 -
Response<ResponseBody> response = myCall.execute();
System.out.println("response code" + response.code());
这篇关于使用Retrofit获取原始HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!