<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anurag Kashyap on Medium]]></title>
        <description><![CDATA[Stories by Anurag Kashyap on Medium]]></description>
        <link>https://medium.com/@anurag-kashyap?source=rss-672ee663781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JeV40RM6_TNsVy_Yl0YrtA.jpeg</url>
            <title>Stories by Anurag Kashyap on Medium</title>
            <link>https://medium.com/@anurag-kashyap?source=rss-672ee663781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:11:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anurag-kashyap/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Retrofit : Detailed Analysis and Explanation - 1]]></title>
            <link>https://itnext.io/retrofit-detailed-analysis-and-explanation-1-4e5a069423e2?source=rss-672ee663781------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e5a069423e2</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Anurag Kashyap]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 19:49:03 GMT</pubDate>
            <atom:updated>2022-10-12T14:08:12.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retrofit : Detailed Analysis and Explanation - 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*KVKeFR1BJbhWaKbs0tnJfg.png" /></figure><p>When creating an Android app, HTTP requests are used to connect to the server, upload or download data, and other things. Numerous open-source HTTP request tools are available, including <a href="https://google.github.io/volley/"><strong><em>Google’s Volley</em></strong></a>,<a href="https://loopj.com/android-async-http/"> <strong><em>loopj’s Android Async Http</em></strong></a><strong><em>, </em></strong><a href="https://square.github.io/okhttp/"><strong><em>OkHttp</em></strong></a><strong><em>,</em></strong> and <a href="https://square.github.io/retrofit/">Square’s <strong><em>Retrofit</em></strong></a>.</p><p>Retrofit, in my opinion, is without a doubt the greatest of these few due to its unique and intelligent design. Considering how minimal retrofit’s code there is, reading its source code will be quite beneficial.</p><h3>1. What is Retrofit ?</h3><p>According to the Retrofit official website:</p><blockquote>A type-safe HTTP client for Android and Java</blockquote><p>Simply put, it is a RESTFUL API request tool built on top of OkHttp, very similar in capability to Google’s Volley but quite different in usage.</p><p>Volley is more basic and simple to use; when the app wants to send an HTTP request, you need to create a Request object, specify the Request with GET, POST, or other methods, an api address, and a callback to handle the response. If the request is a POST, you must additionally set the Request object content and, occasionally, the Header. After adding the <em>Request</em> object to the <strong><em>RequestQueue</em></strong>, checking the Cache, and sending HTTP requests, Volley will then assist you in handling the situation. The code will be difficult to read if an app has a lot of distinct API calls, on the other hand Retrofit allows you to call a Java method to request an API in a simple way, so that the code in the app will be very concise and easy to read</p><h3>2. How to use Retrofit</h3><p>Let’s say you want to request an API to see the information of posts from a website , for example purpose I will use <em>jsonplaceholder here</em></p><p>First, you need to create a Retrofit object and specify the domain name of the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*11ASWyjuYAvb1d3D4W9JFA.png" /><figcaption>Picture: 1</figcaption></figure><p>Next we need an interface based on the calls for the API and will use Java annotations here .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*ffJFlNMphVV65qywwaXYSg.png" /><figcaption>Picture : 2</figcaption></figure><p>Next the retrofit object(picture 1) will be used to create a <strong><em>Jsonplaceholder</em> </strong>object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*oYVeo8jmjXSN0XDk9zhu5g.png" /><figcaption>Picture : 3</figcaption></figure><p>This means that the API that we have to request is <a href="https://jsonplaceholder.typicode.com/posts">https://jsonplaceholder.typicode.com/posts</a></p><p>Next we create a call object to get the data <strong><em>enqueue </em></strong>method is used to asynchronously send the request , if we want to send in a synchronous way we need to use the <strong><em>execute </em></strong>method . The call object also provides other methods like <strong><em>cancel </em></strong>, <strong><em>isCancelled </em></strong>or others to check the status of HTTP request and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*2Dn9-GVLQsH-vl29_-9ivw.png" /></figure><p>See, Retrofit only needs to construct an interface to represent the HTTP request, and then it will allow us to request an API exactly as we would call a Java method. Isn’t that great and incredible? 😀</p><h3>3. The working of Retrofit</h3><p>From the use of Retrofit described above, it is clear that Retrofit is functioning as an adapter by converting a Java interface into an HTTP request and then sending the request via OkHttp.</p><p>AFAIK Volley creates a <strong><em>Request</em></strong><em> </em>object and then puts it into the queue to make an HTTP request . The request is put into separate thread via <strong><em>HttpUrlConnection</em></strong></p><p>So the question is : How does retrofit achieve this ?</p><p>Answer: Java Dynamic proxy</p><p>In Picture 3 you can see that Jsonplaceholder interface is passed as to the create method of the retrofit object and in return it gives Jsonplaceholder object which then completes the call .</p><p>Lets dig deep and get into the create method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hPoNlW5M3bMcppxEvRGQg.png" /></figure><p>you can get the code <a href="https://github.com/square/retrofit/blob/9b32c965ef31275627e35a862f584bcc7b9fa4e5/retrofit/src/main/java/retrofit2/Retrofit.java#L146-L168">here</a>.</p><p>There are lots of things going on here so lets get into it ,</p><p>It initially verifies whether the provided interface is a valid interface by executing the function <strong><em>validateServiceInterface </em></strong>and <strong><em>IllegalArgumentException </em></strong>is thrown if it is invalidinterface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*9CwSMr5f8OEatMW-jBd_KQ.png" /></figure><p>Next create method returns a <strong><em>Proxy.newProxyInstance</em></strong> dynamic proxy object. Now the question is : What is a dynamic proxy?</p><p>Well it’s an advanced topic in itself and you can learn about it from other places but simply put it is a part of Java proxy design pattern and it allows the creation of proxy objects when a program need to extend or modify some functionalities of an already existing class . In this case a proxy object is instantiated instead of the original one . The proxy class only creates a proxy and the actual behavior is modified in its handlers . The handler does its extended work and then goes on to call the original method to let it perform the further task . When an API <strong>interface</strong> instance is created using Retrofit, the instance returned from retrofit is actually a <strong>proxy</strong> class, a <strong>dynamic</strong> implementation of the <strong>interface</strong> at <strong>runtime</strong>.</p><p>The main thing to learn is <strong><em>InvocationHandler ,</em></strong>It is an interface that allows us to intercept any method calls to the object and handle the additional behaviour . This interface is very simple and created just one method <strong><em>invoke</em></strong> that needs to be overridden</p><p>Now coming back to retrofit the <strong><em>newProxyInstance </em></strong>method required 3 parameters</p><ol><li>A classloader of the class : (interface in our case ) passed , now a class loader is basically a part of JRE that is responsible for loading <em>Java</em> classes dynamically to the JVM at runtime .</li><li>List of interfaces of the class : This is required so as to know that when any of the method of these interfaces is invoked , the proxy class will know about it .</li><li>The <em>InvocationHandler </em><strong><em>: This </em></strong>is where the <strong><em>InvocationHandler </em></strong>is implemented and the invoke method is overridden , This invoke method takes in 3 parameters :</li></ol><blockquote>a.) the proxy object : <em>the proxy instance that the method was invoked on</em></blockquote><blockquote>b.) method : <em>instance that corresponds to the interface method that the proxy instance was used to call. The interface in which the method was declared, which may be a super interface of the proxy interface from which the proxy class inherits the method, will be the declaring class of the method object.</em></blockquote><blockquote>c.) args: <em>an array of objects, or </em><strong>null </strong><em>if the interface method doesn’t accept any parameters, that represents the values of the arguments passed in the method call on the proxy instance. Instances of the appropriate primitive wrapper class, such as </em><strong>java.lang.Integer</strong><em> or </em><strong>java.lang.Boolean</strong><em>, are used to encase arguments of primitive types.</em></blockquote><p>Next retrofit uses the<em> java reflection</em> to get the annotation information of the method that has been called and created a <strong><em>ServiceMethod </em></strong>object with the args provided .</p><p>The Retrofit object and Method object are passed to ServiceMethod, which then calls each interface and parser and generates a Request with information about the API’s domain name, path, HTTP request method, request header, status of a body, whether it is multipart, etc.<br>OkHttpCall is the default implementation of the Call interface in Retrofit2, and it by default utilises OkHttp3 as the HTTP request client.</p><p>A Java dynamic proxy is used to resolve the Java method’s annotations, build a Request that is subsequently submitted by OkHttp, and intercept the Java method that is being called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*fu5DgNztANpW2GH0wmzYag.png" /></figure><p>next the object goes into the invoke method which then performs the request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OF87sf0FW864W97cUXp0g.png" /></figure><h3>4. Four pillars of Retrofit</h3><p>1️⃣ <strong><em>Callback &lt; T &gt;</em></strong> : This is where the retrofit returns its call and there are two methods here :</p><ul><li>void onResponse(Response&lt;T&gt; response)</li><li>void onFailure(Throwable t)</li></ul><p>2️⃣ <strong><em>Converter &lt; F , T &gt; : </em></strong>Its main role is to parse the data returned by HTTP into Java objects, mainly Xml, Json , protobuf, etc. You can add the converters you need to use when creating a Retrofit object</p><p>3️⃣ <strong><em>Call &lt; T &gt;</em></strong> : Its main role is to send an HTTP request, the default implementation of Retrofit is <em>OkHttpCall&lt;T&gt;</em>, you can implement your own Call class according to the actual situation</p><p>4️⃣ <strong><em>CallAdapter &lt;T&gt; : </em></strong>As mentioned above, <strong><em>CallAdapter </em></strong>has only one <em>responseType </em>property and one <strong><em>&lt;R&gt; T adapt(Call&lt;R&gt; call)</em></strong> method, and only one implementation class of this interface, <strong><em>DefaultCallAdapter</em></strong>. This class was probably designed to support RxJava</p><h3>5. Executing Http Requests</h3><p>As was previously noted, OkHttpCall implements the Call interface and is the class that calls OkHttp3 to submit an HTTP request. This HTTP request calls for a Request object, which is returned via ServiceMethod’s toRequest method.</p><p>In conclusion, OkHttpCall calls ServiceMethod to obtain a Request object that may be used for execution, waits for the HTTP request to complete, and then passes the response body to ServiceMethod, which can call the Converter interface to convert the response body into a Java object.</p><p>Combining the above, we can see that ServiceMethod contains practically all of the information required for an API request, OkHttpCall needs to obtain a Request object from ServiceMethod, and then after receiving the answer, it also needs to pass in ServiceMethod to convert it into a Java object using the converter passed</p><h3>~~ =&gt;</h3><p>Retrofit very cleverly uses annotations to describe an HTTP request, abstracts an HTTP request into a Java interface, and then uses a Java dynamic proxy to dynamically “parse” the annotations of the interface into an HTTP request, and then executes the HTTP request.</p><p>Retrofit’s functionality relies heavily on Java reflection, and there are actually a lot of details in the code, such as exception catching, throwing and handling, and a lot of Factory design patterns .</p><p>The interface design in Retrofit is just right, giving you more and more flexible ways to handle your needs when you create Retrofit objects, such as using different Converters, using different CallAdapter, which also provides you with the possibility to use RxJava to call Retrofit</p><p>I’ve always believed that it’s unlikely for someone who hasn’t read good code to write good code. Picasso and Retrofit are examples of good code that are extremely extensible, have low coupling, and are easily pluggable .</p><p><em>Part 2 Coming soon with more info</em> …</p><p>🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e5a069423e2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/retrofit-detailed-analysis-and-explanation-1-4e5a069423e2">Retrofit : Detailed Analysis and Explanation - 1</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>