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

  • build.gradle (y sincronizar)

Release

dependencies {

    


    implementation("com.squareup.okhttp3:okhttp:4.9.0")
}

 

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