Android/HttpRequest通信/okhttp3
提供: 初心者エンジニアの簡易メモ
必須
Android 2.3以降
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
インストール
app/build.gradle
dependencies { implementation 'com.squareup.okhttp3:okhttp:3.7.0' }
参考:https://qiita.com/naoi/items/8d493f00b0bbbf8a666c
同期処理
import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; OkHttpClient client = new OkHttpClient(); try { Request request = new Request.Builder().url(url).build(); Call call = client.newCall(request); Response response = call.execute(); ResponseBody body = response.body(); String res = body.string(); Log.i("okhttp3", "res=" + res); } catch (IOException e) { }
同期処理なので、NetworkOnMainThreadExceptionエラーが出る場合はAcyncTask側で処理する必要がある
非同期処理
import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; OkHttpClient client = new OkHttpClient(); // RequestBody requestbodey = new FormBody.Builder() // .build(); Request request = new Request.Builder() .url(url) //.post(requestbodey) .get() .build(); client.newCall(request).enqueue(new Callback() { final Handler mainHandler = new Handler(Looper.getMainLooper()); @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); String callString = call.toString(); Log.i("okhttp3", "res=" + result); } });
非同期なのでメインスレッド側に記述できる