Skip to content

Instantly share code, notes, and snippets.

@just-kip
Created May 11, 2016 13:43
Show Gist options
  • Save just-kip/1376527af60c74b07bef7bd7f136ff56 to your computer and use it in GitHub Desktop.
Save just-kip/1376527af60c74b07bef7bd7f136ff56 to your computer and use it in GitHub Desktop.
OkHttp3 asyncTask example
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
final OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("http://www.mocky.io/v2/573336c90f0000902cead88d")
.build();
AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
return null;
}
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
textView.setText(s);
}
}
};
asyncTask.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment