Reputation: 11
i want connect to url like this "http://192.168.10.xxx/eng..."
and in browser, i can pass by "http:admin:[email protected]"
but when i use android okhttp and connect url
it always response unAuthenticated
i use many api to test,but not have fix it
who can i fix it...please hep me
thanks very much
OkHttpClient client = new OkHttpClient();
String url = "http://192.168.10.254/eng/admin/siteSurvey.cgi";
Request request = new Request.Builder().url(url).build();
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("admin", "admin");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String json = null;
try {
json = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("OKHTTP", json);
}
@Override
public void onFailure(Call call, IOException e) {
}
});
Upvotes: 1
Views: 165
Reputation: 13488
The wiki has an example in the Recipes
https://github.com/square/okhttp/wiki/Recipes#handling-authentication
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
And there are examples in stackoverflow as well.
Upvotes: 1