With OkHttp we can make HTTP request then get response from server:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
Then with Gson lib convert response to object we need.
This is from Square/OkHttp doc:
Its request/response API is designed with fluent builders and
immutability. It supports both synchronous blocking calls and async
calls with callbacks
I read from Stackoverflow:
Retrofit uses OkHTTP automatically if available.
So my questions are:
What, exactly, is Retrofit for?
What Retrofit can do that OkHttp cannot?
I think OkHttp and Gson solve the request API problem,
but what problem does retrofit solve for us?
with OkHttp we can make HTTP request then get response from server... then with Gson lib convert response to object we need
Note that in your code snippet, you skipped two notable steps: generating the URL and actually parsing the JSON using Gson.
So my question is what is exactly Retrofit for?
It is for generating the URL (using type-aware generated code tied to your specific REST API) and actually parsing the JSON using Gson. In other words, it does what you skipped in your code snippet.
Also, for certain types of REST operations (e.g., POST), it helps a bit in assembling what to submit (e.g., generating the encoded form).
By definition, you do not need to use Retrofit. Retrofit is computer code, written by computer programmers. Somebody else could write code to do what Retrofit does.
why Retrofit use OkHttp
Retrofit needs to perform HTTP operations. It uses OkHttp where available, for all that OkHttp provides: HTTP/2 and SPDY support, pluggable interceptors, etc.
You should use retrofit if you are trying to map your server API inside your application (type-safing). Retrofit is just an API adapter wrapped over okHTTP.
If you want to type safe and modularise the interaction code with your API, use retrofit. Apart from that, the underlying performance, request defaults, etc of okHTTP and Retrofit are the same.
Also I would recommend listening to this podcast from Jesse Wilson (developer of major android HTTP clients), where he talks in-depth of the history of development of Apache HTTP client, HTTPURLConnection, okHTTP and Retrofit.
Retrofit vs. OkHttp
The reason is simple: OkHttp is a pure HTTP/SPDY client responsible for any low-level network operation, caching, request and response manipulation, and many more. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit 2 is strongly coupled with OkHttp and makes intensive use of it.
OkHttp Functions: Connection pooling, gzipping, caching, recovers from network problems, sync, and async calls, redirects, retries … and so on.
Retrofit Functions: URL manipulation, requesting, loading, caching, threading, synchronization... It allows sync and async calls.
Retrofit is basically architecture above the OKHTTP, it internally uses OkHttp to make any request , earlier in jave if we want to make any request we have HTTPUrl connection or HTTPS Url connect know retrofit okHttp handles everything ( it divides into packages it marks headers )for us if we need to send some information .
Retrofit is a rest client that is based on restful principle .
->OkHttp is a an HTTP client, which supports HTTP/2 and SPDY.
->Retrofit is a type safe HTTP client for android and java
->OkHttp depends on Okio.
->Retrofit depends on OkHttP,
so Retrofit is basically a wrapper on OKHTTP ,it uses when necessity and can easily manage connect timeout and read timeout just using it’s methods and also adds Interceptor.
Hope I answered !!! happy coding!!!!
for more information refer https://square.github.io/retrofit
OkHttp: An open source HTTP client. HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth; Retrofit: A type-safe HTTP client for Android and Java. Retrofit turns your HTTP API into a Java interface.
OkHttp and Retrofit can be primarily classified as "API" tools.
Some of the features offered by OkHttp are:
• HTTP/2 support allows all requests to the same host to share a socket.
• Connection pooling reduces request latency (if HTTP/2 isn’t available).
• Transparent GZIP shrinks download sizes.
On the other hand, Retrofit provides the following key features:
• URL parameter replacement and query parameter support
• Object conversion to request body (e.g., JSON, protocol buffers)
• Multipart request body and file upload
Related
Exponential Back Off mentioned in Google docs is based on HttpRequest which is removed in SDK 23. I have implemented GCM and i want to integrate this feature without using legacy HttpRequest class. I am using URLConnection to send request. How to implenent Exponential Back Off without using HttpRequest?
I am downloading gigabytes of data (a large number of small files) at a time and would like to optimize the download times by instead using a HTTP request instead of using HTTPS, which is a slower process, especially if repeated thousands of times before each transfer.
What is the default request protocol for the Java AWS SDK and how can I set it to HTTP?
When constructing a client object (For example AmazonEC2Client), you can pass in an optional com.amazonaws.ClientConfiguration object to customize the client's configuration.
Use the below constuctor:
AmazonEC2Client(AWSCredentials awsCredentials, ClientConfiguration clientConfiguration)
Read more here.
Now, while creating the ClientConfiguration object you can use setProtocol() to define the protocol to be HTTP or HTTPS. And accordingly the client object hence created would use that protocol. See here.
My task is to load web site in WebView over HTTPS with unsupported by vanilla Android TLS cipher.
Right now as proof of concept I have implemented apache http client capable of doing http requests to such resources.
What is the best approach to make WebView use my custom client implementation to do all network requests?
Actually, the accepted answer is wrong. You do not get full information; what's missing are request bodies.
So you can implement GET or HEAD requests just fine, but POST requests are trickier.
I haven't seen a good solution for that yet. One I've come across uses JavaScript inserted into the page to collect the POST data, hand it to Java via a binding https://developer.android.com/guide/webapps/webview.html#BindingJavaScript and then performs the request in Java.
Unfortunately, the WebView will try to perform the same request again, so you need to add more hackery to make it work.
Since Android 5.0 (API 21+) you can use WebViewClient.shouldInterceptRequest(WebView, WebResourceRequest) to intercept web requests with full information and perform them with custom HTTP client.
Thanks #Stan for the tip.
I am writing a Java GAE app and relying on URL Fetch to send HTTP requests to other servers (see here. Up until this point, I had been using their HttpUrlConnection interface implementation in order to use the URL Fetch service. However, I am rewriting my app to use the low-level API instead of HttpUrlConnection because I want to send asynchronous HTTP requests.
My question: What is the URL Fetch low level API equivalent of HttpUrlConnection.getResponseMessage():String? Based on what I see from the low-level API javadoc for HTTPResponse, I am not sure of what method I should use. I can get the response code alright, but I'd like to read a useful message along with the code, especially for when an error occurs.
Thanks.
I have this URI http://data.seattle.gov/api/views/vncn-umqp/rows.json of type .json and want to make a GET request to retrieve the data part of the object (see the latter part of the page with "data") for plotting purposes.
Problem is I am not sure whether to use HttpURLConnection, URL,URLConnection or Connection or any other similar resource to receive a successful 200 response. Moreover, this URI's domain provides a REST API right here for request but due to inconsistencies in documentation (for example they use sun.Base64Encoder for encoding user credentials, which is not for use or unavailable) I find it really hard to employ for connection, let alone for data retrieving.
They also use an authentication method with API key but I am not sure which one does the job for the task's simplicity (i.e., which one is necessary only for reading data from this particular URI)
Can anyone provide me the solution on how to make such a request?
You can use Apache HttpClient to make requests to web resources, its included in the Android API. Issuing a GET request is simple enough:
HttpGet get = new HttpGet("http://data.seattle.gov/api/views/vncn-umqp/rows.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
System.out.println(response.getStatusLine());
You can then use a JSON library to parse the response. The client also supports the other HTTP verbs (POST, PUT, DELETE ...).
As to the second part of your question, it was somewhat confusing because it seemed to imply that this REST API was being provided by the same provider of the web service you linked, but it is not. Also, it was not immediately obvious that it is actually a REST client API. You may want to update your question to clear that up. But back on topic, you do not need to use a complicated REST client API for this, just access the content with HttpClient and process it with a JSON library.
Good luck!
I recommend you to use the Google's Gson library to work with JSON files.
http://code.google.com/p/google-gson/
It's very easy to integrate on your project and will ease a lot your work to parse the content of the json file.