2017-02-20 1 views
1

je veux connecter url comme ça "http://192.168.10.xxx/eng ..."URL de connexion inclure le nom et le mot de passe

et dans le navigateur, je peux passer par "http: admin: [email protected]"

mais quand j'utilise okhttp Android et connecter url

il réponse toujours UNAUTHENTICATED

i utiliser beaucoup api pour tester, mais pas Réparez

qui peut je résoudre ce problème ... s'il vous plaît me hep

merci beaucoup

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) { 

     } 
    }); 

Répondre

1

Le wiki a un exemple dans les recettes

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(); 

Et il y a des exemples dans stackoverflow comme bien.

+0

Yuri Schimke, merci de répondre, j'essaie d'utiliser ce matheod, mais sever me répondre 401, j'ai mis à jour mon code, pouvez-vous me dire où je devrais corriger? –