2017-02-20 35 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,我有更新我的代码, 可以请求你告诉我应该在哪里修复?谢谢。 –