Authenticator.setdefault在Java中工作但不在Android中工作(给出401错误)

时间:2015-03-18 02:35:08

标签: java android authentication jsoup

我正在尝试从本地网络URL读取(使用GET)。但是,服务器(在这种情况下是路由器)要求输入用户名/密码,如下所示: enter image description here

我正在使用以下代码进行基本的http身份验证:

Authenticator.setDefault( new Authenticator() {
                      @Override protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication ("admin", "admin".toCharArray());
                      }
                    });

                try {
                    Document doc = Jsoup.connect("http://192.168.0.100:5000/location_list.cgi?action=load").ignoreHttpErrors(isRestricted()).get();
                    System.out.println(doc);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

它作为Java应用程序运行时工作正常。但是,在Android应用程序中,它提供 401 UnAuthorized 错误代码。

我甚至试过了 身份验证:基本[“admin:admin”.toBASE64encoding] 但问题是一样的。请帮助。

1 个答案:

答案 0 :(得分:0)

我的朋友,我遇到了同样的问题,最后我找到了一个解决方案:

org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
                GetMethod getMethod = new GetMethod(mCameraVideo.getCameraIP() + "tmpfs/auto.jpg");
                //int status = client.executeMethod(getMethod);
                UsernamePasswordCredentials upc = new UsernamePasswordCredentials(mCameraVideo.getUserName(), mCameraVideo.getPassword());
                AuthScope as = new AuthScope(mCameraVideo.getHost(), mCameraVideo.getPort(), "");
                client.getState().setCredentials(as, upc);
                int status = client.executeMethod(getMethod);
                // getMethod.releaseConnection();

另请参阅:https://code.google.com/p/android/issues/detail?id=9579

相关问题