连接URL包括名称和密码

时间:2017-02-20 07:27:29

标签: android http url okhttp

我希望像这样“http://192.168.10.xxx/eng ...”

连接到网址

在浏览器中,我可以通过“http:admin:admin@192.168.10.xxx”

但是当我使用android okhttp并连接url

它始终响应unAuthenticated

我使用很多api来测试,但没有修复它

谁能解决它...请帮我

非常感谢

   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 个答案:

答案 0 :(得分:1)

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

还有stackoverflow中的例子。