2017-02-20 37 views
1

我想連接到URL這樣的「http://192.168.10.xxx/eng ...」連接URL包括名和密碼

,並在瀏覽器中,我可以通過「HTTP:管理員:[email protected]

但是當我使用Android okhttp並連接網址

它總是響應未經驗證的

我用很多的API來進行測試,但沒有修復它

誰可以我解決它......請HEP我

非常感謝

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

     } 
    }); 

回答

1

維基已在食譜

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

一個例子,有在計算器的例子作爲好。

+0

Yuri Schimke,謝謝你的回答,我嘗試使用這個數學方法, 但服務器響應我401,我有更新我的代碼, 可以請求你告訴我應該在哪裏修復?謝謝。 –