Uso de OkHttp en Kotlin
OkHttp
OkHttp
Recipies: Asynchronous Get
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(responseBody.string()); } } }); }
Using OkHttp
Sending and Receiving Network Requests
Asynchronous Network Calls
Updating Views on UIThread
Ejemplo: Descarga de un fichero usando OkHttp
Añadir la biblioteca de okhttp a build.gradle (y sincronizar)
Release
dependencies { implementation("com.squareup.okhttp3:okhttp:4.12.0") }
Añadir el switch (para elegir entre AsyncTask y OkHttp)
Si está activo el switch, descargar el fichero usando OkHttp y, si no lo está, realizar la descarga usando AsyncTask
override fun onClick(view: View) { try { url = URL(binding.editText.text.toString()) if (binding.switch1.isChecked) { //descarga usando OkHttp OkHTTPdownload(url) } else // descarga usando AsyncTask y Java.net download(url) } catch (e: MalformedURLException) { e.printStackTrace() showError(e.message) } catch (ex: IOException) { showError(ex.message) } }
Realizar la descarga
private fun OkHTTPdownload(web: URL) { }
mostrar la respuesta
private fun showResponse(message: String) { }
Comprobar el funcionamiento usando un servidor web en Internet y un servidor local:
Diferencia entre OkHttp y HttpUrlConnection?
Ejercicio de la tarea online: Divisas
https://dam.org.es/ficheros/cambio.txt
https://dam.org.es/ficheros/rate.txt
Más información
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.