Make an Http Request With Android

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

  • Retrofit
  • OkHttp
  • Volley
  • HttpUrlConnection

Original Answer

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

How can I make a simple HTTP request in MainActivity.java? (Android Studio)

You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.

Android force this behaviour by throwing an exception if you use the HttpUrlConnection object from the main thread.

You should then make your network request in the background, and then update the UI on the main thread. The AsyncTask class can be very handy for this use case !

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}

protected void onProgressUpdate(Integer... progress) {
}

protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}

And you start this process this way:

new GetUrlContentTask().execute(sUrl)

HTTP Request in Android with Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection
which is part of the Java SDK:

fun sendGet() {
val url = URL("http://www.google.com/")

with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET

println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

inputStream.bufferedReader().use {
it.lines().forEach { line ->
println(line)
}
}
}
}

Or simpler:

URL("https://google.com").readText()

How to make an http request in android when screen is off?

use Thread instead of AsyncTask e.g

Thread t = new Thread({
public void run(){
.....
your code
}
});
t.start();

Simple HTTP request example in Android using Kotlin

I suggest you to use the official recommendation of OkHttp, or the Fuel library for easier side and it also has bindings for deserialization of response into objects using popular Json / ProtoBuf libraries.

Fuel example:

// Coroutines way:
// both are equivalent
val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
val (request, response, result) = "https://httpbin.org/ip".httpGet().awaitStringResponseResult()

// process the response further:
result.fold(
{ data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
{ error -> println("An error of type ${error.exception} happened: ${error.message}") }
)

// Or coroutines way + no callback style:
try {
println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
} catch(exception: Exception) {
println("A network request exception was thrown: ${exception.message}")
}

// Or non-coroutine way / callback style:
val httpAsync = "https://httpbin.org/get"
.httpGet()
.responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
println(data)
}
}
}

httpAsync.join()

OkHttp example:

val request = Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build()

// Coroutines not supported directly, use the basic Callback way:
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}

override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")

for ((name, value) in response.headers) {
println("$name: $value")
}

println(response.body!!.string())
}
}
})


Related Topics



Leave a reply



Submit