OkHttp

uso de 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

First, we must instantiate an OkHttpClient and create a Request object.

// should be a singleton
OkHttpClient client = new OkHttpClient();
 
Request request = new Request.Builder()
                     .url("http://publicobject.com/helloworld.txt")
                     .build();

Asynchronous Network Calls

We can also make asynchronous network calls too by creating a Call object, using the enqueue() method, and passing an anonymous Callback object that implements both onFailure() and onResponse().

// Get a handler that can be used to post to the main thread
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }
 
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        } else {
            Toast.makeText(getActivity(), "Connection failed", Toast.LENGTH_LONG).show();
        }
    }
});

Updating Views on UIThread

OkHttp normally creates a new worker thread to dispatch the network request and uses the same thread to handle the response. It is built primarily as a Java library so it does not handle the Android framework limitations that only permit views to be updated on the main UI thread.

For this reason, if you try to access or update views from outside the main thread in the Callback, you will probably receive an exception: android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its
views
. Read more about the relationship between the main thread and views here.

If you need to update any views from within a response, you will need to use runOnUiThread() or post the result back on the main thread:

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        // ... check for failure using `isSuccessful` before proceeding
 
        // Read data on the worker thread
        final String responseData = response.body().string();
 
        // Run view-related code back on the main thread
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    TextView myTextView = (TextView) findViewById(R.id.myTextView);
                    myTextView.setText(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
       }
    }
});

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.10.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
public void onClick(View view) {

    try {
        url = new URL(binding.editText.getText().toString());
        if (binding.switch1.isChecked())
            // descarga usando OkHttp
            descargaOkHTTP(url);
        else
            // descarga usando AsyncTask y Java.net
            descarga(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        mostrarError(e.getMessage());
    } catch (IOException ex) {
        mostrarError(ex.getMessage());
    }
}

Realizar la descarga y mostar la respuesta

private void descargaOkHTTP(URL web) {
    inicio = System.currentTimeMillis();
    final OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(web)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            Log.e("Error: ", e.getMessage());

            mostrarRespuesta("Fallo: " + e.getMessage());
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            try (ResponseBody responseBody = response.body()) {
                if (!response.isSuccessful()) {
                    //throw new IOException("Unexpected code " + response);
                    mostrarRespuesta("Unexpected code: " + "<br>" + response);
                } else {
                    // Read data on the worker thread
                    final String responseData = response.body().string();
                    //Toast.makeText(getApplicationContext(), datos, Toast.LENGTH_SHORT).show();
                    mostrarRespuesta(responseData);
                }
            }
        }
    });
}

private void mostrarRespuesta(String message) {
    fin = System.currentTimeMillis();
    // Run view-related code back on the main thread
    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            binding.webView.loadDataWithBaseURL(String.valueOf(url), message, "text/html", "UTF-8", null);
            binding.textView.setText("Duración: " + String.valueOf(fin - inicio) + " milisegundos");
        }
    });
}

Tarea online

https://dam.org.es/ficheros/cambio.txt

https://dam.org.es/ficheros/rate.txt

Código: ConexionAsincrona

Más información:

OkHttp Android Example Tutorial

Deja una respuesta