Is it ok to use the same HttpClient *object* for several execute method calls?
(assuming I'm not executing the HttpGet requests simultaneously)
You can use AndroidHttpClient to do that with api 8 or above. See this link to know how to work with AndroidHttpClient: http://www.java2s.com/Code/Android/Network/CreateHttpconnection.htm
Otherwise, you can use ThreadSafeClientConnManager. "This connection manager doesn’t handle a single connection, but a pool of them, where each connection can be taken from the pool, allocated to a thread (which then has exclusive access to it), and returned to the pool once the thread yields it. If the same or another thread claims a connection for the same route, then a connection can be immediately reused from the pool without the need to first close and reopen it, thereby avoiding the overhead of the handshake performed by HTTP when establishing a new connection.ThreadSafeClientConnManager for instance sets the default values for the maximum number of total connections to 20, and the maximum number of connections per route to 2."
- from "Android in Practice"
You can see this link to know about ThreadSafeClientConnManager: http://massapi.com/class/th/ThreadSafeClientConnManager.html
It's not safe to use same HttpClient, but you can use AndroidHttpClient,
AndroidHttpClient client = AndroidHttpClient.newInstance("xxxx");
AndroidHttpClient is thread safe.
Related
I have to send four different request in an api at the same time. Do i need to make AsyncTask background thread for each request or all request could be done through a single AsyncTask. Can somebody please help.
This is a concurrency issue. There is literally dozens of ways to do this in Android. I've written almost every single one for courses that cover this material... and even then it isn't 'simple'.
I'd personally make use of HaMeR (Handler, Messages, Runnable) framework of Android. Create 4 runnables and have them post their results to a Handler.
However... That isn't the easiest to implement. and would require you to understand how to safely create your own custom handler (making use of WeakReference properly, etc.)
Therefore, I'd recommend running the asyncTask(s) on the executorService
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); The default thread pool executor should start with 4 threads (I believe off-hand without looking it up).
I am assuming you are using HttpURLConnections. Unfortunately each of those connections, as specified in the documentation, is capable of handling only a single request.
However, you can (and possibly should) still perform all your requests in a single AsyncTask. Each AsyncTask will require the creation of a new thread which takes lots of time and resources. So don't listen to anyone who tells you to create a new task for each request.
You also have the option of exploiting HTTP persistence. If you add the header Connection: Keep-Alive to your request via connection.setRequestProperty("Connection", "Keep-Alive");, you will be able to send multiple requests over the same connection and save a lot of time and resources.
It's a little complicated in Java, because of the one-request-per-httpurlconnection rule, but it can be done. First, when you are done with your first request's HttpURLConnection do not close that connection. Then, to create the next connection, call url.openConnection() on the same URL object that you used to create your first HttpURLConnection. The JVM will know to reuse that connection if possible to save bandwidth.
You also have the option of using HTTP/2.0 multiplexing, which allows you to send multiple requests literally at the same time. Unfortunately I am not yet well versed enough in HTTP/2.0 to tell you exactly how to make use of this, but the multiplexing feature was included to solve exactly this problem.
My question is pretty simple. Its whether it is safe to have one instance of a urlconnection, open it and use multilpe requests on that instance (GETs and POSTs). I've been noticing some bad latency in my requests, and I'm thinking that this has a lot to do with it. As of now, each activity creates its own instance of my httpurlconnection class which opens up a new connection per request.
https://hc.apache.org/httpcomponents-client-4.3.x/android-port.html
Check out samples at the link for "thread pool connection". Using a good, threaded client that u implement to produce async type exec stack, you may config the number of connections per domain.
Async + threadpooled connections will speed your network bottleneck
My app is to send multiple http requests for fetching data.
Every request must to be executed concurrently.
Since, There is only one HttpClient's object for each concurrently executed request. Would there be any issues that may affect the concurrency.
HttpClient is kind of an oddball on Android. In the past I used a pool with threads to have multiple and/or concurrent connections.
However Koushik Dutta (from CyanogenMod, ClockworkMod) made a very nice AsyncHttp library. The library is very simple to use and probably will handle all of your needs.
I have an application that uses apache's HttpClient to get websites. It has 2 threads - UI thread (where user can order downloading a subpage) and other that every x seconds refreshes main page by downloading it with use of HttpPost.
It appears that there is some synchronization problem(query started ends immediately with socket error), when during reloading user starts a download of another page (I use the same DefaultHttpClient for both queries). Important thing is that the page requires cookies (user has its session).
My question is:
Should I use one HttpClient and queue of queries not to let them happen in the same moment?
Or maybe each thread should have it's own HttpClient and they should have common context?
Or there is any other way that eliminates this error?
I also want to ask if you know a faster HTML parser than JSoup. It is pretty fast, I agree, but maybe there's something better?
You can make HttpClient thread safe by specifying a thread safe client manager. (Threadsafe in the sense that two or more threads can interact with it without getting above error message)
http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html
You should have HTTPClient for each thread. If you are doing any common task (Might be danger).
To make it thread safe you should put synchronized block at method level or where you have common task to do.
Recommendation : While working with thread keep the tasks as much separated as possible. If at all you have some common task , make use of synchronized block
AndroidHttpClient is said to be thread safe. Just to make sure - does it means that I can use a single client instance in my app for all the HTTP requests?
Is there a reason not to do so?
In its source code, I noticed that it uses BasicHttpContext and not SyncBasicHttpContext. Does the ThreadSafeClientConnManager take care of all threading complexity?