I have searched everywhere but I couldn't find my answer, is there a way to make an simple HTTP request? I want to request an PHP page / script on one of my website but I don't want to show the webpage.
If possible I even want to do it in the background (in an BroadcastReceiver)
The most simple way is using the Android lib called Volley
You can send a http/https request as simple as this:
In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.
This is the new code for HTTP Get/POST request in android.
HTTPClient
is depricated and may not be available as it was in my case.Firstly add the two dependencies in build.gradle:
Then write this code in
ASyncTask
indoBackground
method.As none of the answers described a way to perform requests with OkHttp, which is very popular http client nowadays for Android and Java in general, I am going to provide a simple example:
The clear advantage of this library is that it abstracts us from some low level details, providing more friendly and secure ways to interact with them. The syntax is also simplified and permits to write nice code.
UPDATE
This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:
Original Answer
First of all, request a permission to access network, add following to your manifest:
Then the easiest way is to use Apache http client bundled with Android:
If you want it to run on separate thread I'd recommend extending AsyncTask:
You then can make a request by:
Regards
For me, the easiest way is using library called Retrofit2
We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :
And the best is, we can do it asynchronously easily using enqueue method