OkHttpでいろいろやろうとしたときに調べたものを列挙(随時追記)
Basic認証
OkHttpClientにAuthenticatorを設定しておくとリクエストの際にそれをつかって認証してくれる
OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
String credential = Credentials.basic("ユーザー名", "パスワード");
return response.request().newBuilder().header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
SSLのオレオレ証明書を許可する(SSLエラーを無視する)
SSL証明書の検証を行わないようにするのと、実際にアクセスするホスト名の検証を行わないようにすればいけます。
try {
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client.setSslSocketFactory(sslSocketFactory);
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
Cookie管理
Basic認証と同じような感じでOkHttpClientにCookieManagerを設定しておけばクッキー管理をしてくれる
CookiePolicyは以下の3つから選べる
- CookiePolicy
- ACCEPT_ALL (すべての Cookie を受け入れる)
- ACCEPT_NONE (Cookie をまったく受け入れない)
- ACCEPT_ORIGINAL_SERVER (元のサーバーからの Cookie だけを受け入れる)
ただしCookieManagerは、次回アプリ起動時には空になっているので要注意
OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);