Вот код, который я использую, на стороне сервера все в порядке, так как он работает с HttpURLConnection и bare-bones-digest (я больше не использую его, поскольку сервер ограничен 100 соединения и HttpURLConnection обрабатывают повторное использование соединения) Со следующим кодом я всегда получаю сообщение: Несанкционированный код: 401
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static String m_user; // Set elsewhere
private static String m_password; // Set elsewhere
private static OkHttpClient getUnsafeOkHttpClient() {
// For test purpose
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
// Called reflectively by X509TrustManagerExtensions.
public void checkServerTrusted(X509Certificate[] x509Certificates, String authType, String host) {
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder.build();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
Функция вызывается с тайм-аутом = 1000, isPost = true, digestAuth = правда, данные json формат:
private void testConnect(int timeout, final String str_url, boolean isPost, boolean digestAuth, String data)
{
OkHttpClient client = getUnsafeOkHttpClient(); // For test purpose
OkHttpClient.Builder clientBuilder = client.newBuilder();
clientBuilder.connectTimeout(timeout, TimeUnit.MILLISECONDS);
clientBuilder.writeTimeout(timeout, TimeUnit.MILLISECONDS);
clientBuilder.readTimeout(10, TimeUnit.SECONDS);
if(digestAuth) {
final DigestAuthenticator authenticator = new DigestAuthenticator(new Credentials(m_user, m_password));
final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
clientBuilder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache));
clientBuilder.addInterceptor(new AuthenticationCacheInterceptor(authCache));
}
clientBuilder.build();
Request request = new Request.Builder()
.url(str_url)
//.header("Accept", "application/json")// todo Add Headers ?
.build();
Request.Builder requestBuilder = request.newBuilder();
if(isPost) {
RequestBody body = RequestBody.create(data, JSON);
requestBuilder.post(body);
}
requestBuilder.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(myClass.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) {
if (!response.isSuccessful()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(myClass.this, response.message() + " code: " + response.code(), Toast.LENGTH_SHORT).show();
}
});
} else {
if(response.code() == HttpURLConnection.HTTP_OK) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(myClass.this, "OK", Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
Спасибо, скажите мне, что не так.