Here is the following code, I try to do a basic auth with okhttp by following some example. The normal HTTP request (commented out) works fine so it's not a network issue or anything like that. The main fetch code which would try to authenticate does not try to connect to the webserver at all. There is nothing in the webservers log, I don't get anything if I checking on port 80 with tcpdump.
Any idea from those who are using OkHTTP?
package com.example.webclient;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class MainActivity extends AppCompatActivity {
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// works
// client = new OkHttpClient();
// run("http://192.168.1.1/old");
//does not work
String url = "http://192.168.1.1/new";
try {
fetch(url, "user", "pass");
} catch (Exception e) {
e.printStackTrace();
}
}
private void run(String url) {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response){
String url = response.body().toString();
//your code here
}
});
}
public static Response fetch(String url, String username, String password) throws Exception {
OkHttpClient httpClient = createAuthenticatedClient(username, password);
// execute request
return doRequest(httpClient, url);
}
private static OkHttpClient createAuthenticatedClient(final String username,
final String password) {
// build client with authentication information.
OkHttpClient httpClient = new OkHttpClient.Builder().authenticator(new Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
if (responseCount(response) >= 3) {
return null;
}
return response.request().newBuilder().header("Authorization", credential).build();
}
}).build();
return httpClient;
}
private static Response doRequest(OkHttpClient httpClient, String anyURL) throws Exception {
Request request = new Request.Builder().url(anyURL).build();
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
System.out.println(response.body().string());
return response;
}
private static int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
}