Use HttpUrlConnection with volley - android

I read everywhere that volley will use either HttpUrlConnection for newer versions api or HttpClient for older version and I'm trying to tell volley to only use the HttpUrlConnection.
My main goal is to setup volley to execute requests using a cookie I have in store, and to do that I know I need to set the HttpUrlConnection with the cookie and then pass it to volley to use as the default implementation.
So far so good but I have no idea how to start HttpUrlConnection and add the cookie to it.
Can someone please give me a small example of how to initialise HttpUrlConnection and add a cookie to it and then pass it on to volley?
I was able to perform such a request on HttpUrlConnection itself and it worked but how do I set it up to use with volley?
URL urlLink = new URL(url2);
HttpURLConnection conenction = (HttpURLConnection)urlLink.openConnection();
conenction.setRequestProperty("Cookie", cookie);

I read everywhere that volley will use either HttpUrlConnection for newer versions api or HttpClient for older version and I'm trying to tell volley to only use the HttpUrlConnection.
This is correct. See lines 54-60 of the Volley source. If your app is running on a device using Gingerbread (API level 9) or higher, it is already using HttpUrlConnection for all requests.
If you really want to use your own HttpUrlConnection instance for your requests, you will need to implement your own HttpStack (see Volley's HurlStack for an example). You can use Volley# newRequestQueue(Context, HttpStack) to tell Volley to use your custom stack.
There are a number of alternatives for sending cookies however. I recommend checking out this question for some of those alternatives.

Related

Difference between okhttp and httpurlconnection?

What are the differences between these 2 libraries?
How I understood there is a difference between these 2 lib also because Volley uses httpurlconnection and Retrofit the okhttp....
But I don't understand the difference between them and pros and cons of both solutions. When is okhttp better and when httpurlconnection?
I would like to know so I know when should I use them.
EDIT:
Why does android use okhttp for the httpurlconnection? before httpurlconnection was not using okhttp if I am not wrong
Pros of okHttp
OkHttp can be customized for every request easily — like timeout customization, etc. for each request.
OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails.
Complete analytics of any request can be obtained. You can know bytes sent, bytes received, and the time taken on any request. These analytics are important so that you can find the data usage of your application and the time taken for each request, so you can identify slow requests.
Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.
OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.
HttpURLConnection
Advantages:
Lightweight APIs help in easier management and reduces compatibility issues.
Automatic handling of the caching mechanisms, with the help of
HttpResponseCache.
Reduces the network usage and also, the battery consumption.
Query Parameter:
URI baseUri = new URI("www.exemple.com/search");
URI uri = applyParameters(baseUri, "word","java");
HttpURLConnection connection =
(HttpURLConnection) uri.toURL().openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() ==
HttpURLConnection.HTTP_OK) {
// ...
}
Android Headers Example:
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);
OkHttp
Advantages:
Connection pooling
Gziping
Caching
Recovering from network problems
Redirects
Retries
Support for synchronous and asynchronous calls
Query Parameter:
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://httpbin.org/get").newBuilder();
urlBuilder.addQueryParameter("website", "www.journaldev.com");
urlBuilder.addQueryParameter("tutorials", "android");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
Android Headers Example:
Request request = new Request.Builder()
.header("Authorization", "replace this text with your token")
.url("your api url")
.build();
The API's are different, personally I prefer the OkHttp ones.
Note that starting from Android 4.4, the networking layer (so also the HttpUrlConnection APIs) is implemented through OkHttp.

How to check whether url scheme is Http or Https and create URLConnection depending on it

So basically right now my app is configured to use https because in the "release" it will use a self signed certificate and obviously also use Https.
My current testsystem (few more features) doesn't use https but http instead. I thought it would be kinda nice to have some type of method to check whether the given URL is Http or Https and depending on the result create the right URLConnection.
My current problem is that I don't know what the method should exactly look like. I thought about using if-statements in the methods which connect to my server but there might be a better solution.
Help would be appreciated.
How about this:
URLUtil.isHttpUrl(String url)
URLUtil.isHttpsUrl(String url)
See also: http://developer.android.com/reference/android/webkit/URLUtil.html
If you don't want to do a manual check you can use a 3rd party library like this one: http://square.github.io/okhttp/ which allows you a simple:
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();

Android connect to Mysql database tutorial

Does anybody know a complete and working tutorial about how to retrieve data from MYSQL and display it in Android? I'm asking this because all the tutorials I found are older than API 22 and from API 22 the HttpClient is deprecated. And I'm a new Android Developer so I can't write any code on my own. :)
HttpClient
Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
This interface was deprecated in API level 22.
Please use openConnection() instead.
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.
Please visit this webpage for further details.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.
Uses of this class follow a pattern:
Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
For example, to retrieve the webpage at http://www.android.com/:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Please visit this webpage for further details.
http://developer.android.com/reference/java/net/HttpURLConnection.html
urlconnection tutorials, can visit this websites
+http://www.vogella.com/tutorials/AndroidNetworking/article.html
+http://javatechig.com/android/android-networking-tutorial

HTTP GET url with Json parameters in Android

I am having the following API call:
http://rollout.gr/api/?query={%22search%22:%22places%22,%22page%22:1}
This API call is executed correctly in my browser. But when I use a DefaultHttpClient to execute this url in my Android application, I get a null response.
I suppose the problem is the JSON data in the HTTP url. Thus, I would like to ask which is the proper way to handle such url in an Android application?
Thanks a lot in advance!
The accolades aren't valid URL characters. The browser is userfriendly enough to automatically URL-encode them, but DefaultHttpClient isn't. The correct line to use from code is:
http://rollout.gr/api/?query=http://rollout.gr/api/?query=%7b%22search%22:%22places%22,%22page%22:1%7d
Note the encoding for the accolades (%7b, %7d).
Your problem may be the strictmode here.
I recommend to do http request in threads or asynctasks. strictmode doesnt let app do http reauest in uithread. maybe your console shows a warning and you get null from http response because of this.
This project may solve your problem:
http://loopj.com/android-async-http/
Not knowing your particular HTTP initialization code, I'm going to assume you didn't provide an explicit JSON accept header. A lot of REST endpoints require this.
httpget.setHeader("Accept", "application/json");

How to invoke a method in a session bean from an Android client?

I want to know whether it is possible to create an Android application to communicate with a session bean and invoke a method. if so can anybody explain how? or else can i invoke that method in the EJB with a JSP/servelet and call the JSP/Servelet with Android clients.. examples are highly appreciate
Thanks !!!
It is possible to communicate with Servelet in Android using HttpClient, HttpPost and HttpGet classes in android..
It is in theory relatively simple. Servlets can be configured by web.xml or #WebServlet annotation to get executed on a certain request URL. On a HTTP GET request the doGet() method will be executed. On a HTTP POST request, the doPost() method will be executed. The business logic which the servlet executes can depend/rely on the presence of HTTP request parameters and/or the request URI pathinfo.
All you need to do is to fire a HTTP request with the right URL and/or the right request parameters and/or the right pathinfo to let the servlet execute the desired job.
The basic Java API offers the java.net.URL and java.net.URLConnection for this. A simple HTTP GET request can be executed as follows:
InputStream response = new URL("http://example.com/servleturl?foo=bar&bar=foo").openStream();
// ...
Firing HTTP POST requests is a bit more complex. It can be done with java.net.URLConnection as outlined in this mini-tutorial, but Android also ships with Apache HttpComponents Client which allows firing and handling HTTP requests with less lines of code and more self-explaining code.
On http://androidsnippets.org you can find a lot of examples with HttpClient.

Categories

Resources