How to log request and response body with Retrofit-Android?
I used setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG"))
, it helped me.
UPDATE.
You can also try for debug purpose use retrofit.client.Response
as response model
Retrofit response body filed retun null, but logging interceptor showing full response in logact
I resolved this issue by adding kotlin model data class member filed default value. I don't know what is the reason behind this,
Old data class
data class BannerRes(
@SerializedName("actionType")
val actionType: Int?,
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("activity")
val activity: String?,
@SerializedName("error")
val error: Boolean?,
@SerializedName("id")
val id: String?,
@SerializedName("imageUrl")
val imageUrl: String?,
@SerializedName("msg")
val msg: String?,
@SerializedName("visible")
val visible: Boolean?
)
Modified or data class with member field default value which fix my problem
data class BannerRes(
@SerializedName("error") var error : Boolean = true,
@SerializedName("msg") var msg : String? = null,
@SerializedName("id") var id : String? = null,
@SerializedName("activity") var activity : String? = null,
@SerializedName("imageUrl") var imageUrl : String? = null,
@SerializedName("actionUrl") var actionUrl : String? = null,
@SerializedName("actionType") var actionType : Int = 0,
@SerializedName("visible") var visible : Boolean = false
)
Logging with Retrofit 2
In Retrofit 2 you should use HttpLoggingInterceptor.
Add dependency to build.gradle
. Latest version as of October 2019 is:
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
Create a Retrofit
object like the following:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://backend.example.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(ApiClient.class);
In case of deprecation warnings, simply change setLevel
to:
interceptor.level(HttpLoggingInterceptor.Level.BODY);
The above solution gives you logcat messages very similar to the old ones set by
setLogLevel(RestAdapter.LogLevel.FULL)
In case of java.lang.ClassNotFoundException
:
Older Retrofit version might require an older logging-interceptor
version. Take a look at comments sections for details.
Retrofit 2.x : Log Header for request and response
May it help someone ...
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Add both to see complete logs and add this interceptor at the last (don't know why but its like this).
Getting Request body content using Retrofit 2.0 POST method
I have got it working from this link
Retrofit2: Modifying request body in OkHttp Interceptor
private String bodyToString(final RequestBody request) {
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if (copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
Retrofit dependencies i am using are
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
Retrofit2 Kotlin Response body gone to other file
well, little count of searching days, asking on this site and i get it. This is my solution, may be it can help to someone.
First of all i add OkHttpClient. It gave to me information about response. I saw, that my response is came to me normally, but i can't work with it. So, next work - create normally Responce file. Now i can do it on Kotlin, so i got it. My new files:
MainActivity :
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
apiCall()
}
private fun getClient(): Retrofit? {
val TEST_URL_API = "http://localhost:8080/api/"
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.build()
return Retrofit.Builder()
.baseUrl(TEST_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build()
}
private fun apiCall() {
val call = getClient()!!.create(Api::class.java).createUser(
DataModal()
)
call.enqueue(object : Callback<UserResponse> {
override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
val peremennayaResponsa = response.body()
Log.i(TAG, "LOG AND RESULT: body = $peremennayaResponsa")
Log.i(TAG, "headersы = ${response.headers()}")
}
override fun onFailure(call: Call<UserResponse>, t: Throwable) {
Log.i(TAG, "Ошибка запроса = ${t.localizedMessage!!.toString()}")
Toast.makeText(this@MainActivity, t.localizedMessage!!.toString(),
Toast.LENGTH_SHORT).show()
}
})
...
Api.kt :
interface Api {
@Headers("Content-Type: application/json;charset=UTF-8")
@POST("map")
fun createUser(
@Body dataModal: DataModal
) : Call<UserResponse>
And much more intrsting, UserResponse.kt:
data class UserResponse(
val response: Any
)
Why it is intresting? So, my response habe raw body like {"error":null,"response":{"list":{"txtfiles":[{**info that i need**
, and when i ask Application to do log in var i got an error like Expected a string but was BEGIN_OBJECT
. But i solved it, given full response parameter Any, and now i will write my full response in .txt file, parse it and work with info that i needed.
Thank you for reading, and helping
Happy coding :)
How do I save and accumulate the request body data using Retrofit?
See examples like https://stackoverflow.com/a/38525843/1542667
which use MockWebServer just as a way to access RecordedRequest
Related Topics
Android Studio Stuck on "Gradle: Resolve Dependencies '_Debugcompile'" or 'Detachedconfiguration1'
How to Use Android Progressbar in Determinate Mode
Transparent Alertdialog Has Black Background
Android: Open Activity Without Save into the Stack
Differencebetween @Id and @+Id
Android: Asynctask to Make an Http Get Request
How to Display Map in Android with Marker
Android Toggle Button Custom Look
Android Resources$Notfoundexception: Resource Id #0X7F030027
Getting MAC Address in Android 6.0
How to Send File Using Bluetooth on Android Programatically
How to Handle Ontouch Event for Map in Google Map API V2
Android: Disable Soft Keyboard at All Edittexts
How to Handle Outofmemoryerror
How Does One Check If a Table Exists in an Android SQLite Database
Detect Connectivity Change in Android 7 and Above When App Is Killed/In Background
Google Glass Gdk: How to Communicate with Android Device
How to Implement Draggable Map Like Uber Android, Update with Change Location