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; String url = "https://api.github.com/feeds"; 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 android.os.Handler; import android.os.Looper; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; String url = "https://api.github.com/feeds"; 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); } });
非同期なのでメインスレッド側に記述できる
参考:http://nandarou.hateblo.jp/entry/2017/05/23/180728
SSLHandshakeException SSL handshake aborted Failure エラーが起こる場合
Android 4.4でエラーが起こるらしい(Android4.1.1で自分はこのエラーを確認した)
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build();
OkHttpClient client = new OkHttpClient.Builder() .connectionSpecs(Collections.singletonList(spec)) .build();