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.
Related
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
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 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.
I'm a little unfamiliar both with the Servlet API and Apache Http Components.
I need to handle an incoming POST request with unknown data (although probably the result of a form submission) using HttpServlet.doPost() which I've implemented, and request the same posted information from another URL, effectively acting as a relay for the HTTP POST. I then need to convert the response to a String (it will be text/html) and process it further before returning it to the web browser that requested it from me.
Due to my unfamiliarity with these libraries, its not clear to me how to handle issues like the content-type of the posted data, and also avoiding any problems due to neglecting to release resources.
Can anyone provide any pointers on this?
You should start by having a look at HttpClient class from apache API.
It will handle both get and posts as needed and later you could feel its request with the data you receive in your own servlet.
I 'm getting 620 error response codes back from the google maps geocoding api if i send the request directly from my app engine servlet, so i have no choice but to use a proxy to receive a successful response. I set up a proxy server, and ive tested it from several computers. Now, all I want to do is make a url request from my GAE servlet through my proxy.
I've tried every possible solution out there and none of them work....
-java.net.Proxy isnt supported in the app engine runtime...
-setting properties as follows:
Properties props = System.getProperties();
props.put("http.proxyHost", "proxyhostname");
props.put("http.proxyPort", "proxyhostport");
didnt do anything.
What is the easiest way to send an http GET via a proxy in app engine?
It seems like this is not possible: Google's App Engine APIs don't support it. Using a third-party library (like Apache's HTTPCore/HTTPClient) or writing it yourself is not possible because essential network classes like java.net.Socket are not whitelisted.
Not sure why you can't access the Google Map API, but if that really does not work, your only choice is to write some application on your proxy server that responds to normal HTTP requests and then forwards them to Google Maps.
Update: Googled a bit, seems like a well-known problem: the Map API has a limit of 2500 requests per day and IP, and this is limit is reached quickly on GAE where you share your IP with many other applications. The only thing you can do is move the requests to the client, use some proxy with own IP, or use a different service.