代码之家  ›  专栏  ›  技术社区  ›  Nic

Android JAVA到SharePoint 2013 NTLM 401未授权

  •  2
  • Nic  · 技术社区  · 9 年前

    我是Java新手。因为我的公司需要为SharePoint 2013创建一个应用程序。我一直收到错误401。我在很多网站上进行了搜索,但我就是无法正常工作。

    我使用的代码如下:

     StringBuilder sb = new StringBuilder();
        SSLContext sslContext = null;
    
        // Error Handling
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
    
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }}, new SecureRandom());
    
            // Credential
            NTCredentials credentials = new NTCredentials("username", "password", "Hostname", "domain");
            AuthScope scope = new AuthScope("Hostname", 17963);
            //KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme sch = new Scheme("https", socketFactory, 17963);
    
            DefaultHttpClient httpClient = new DefaultHttpClient();
    
            httpClient.getCredentialsProvider().setCredentials(scope, credentials);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    
    
            // HttpHost host = new HttpHost("HostName", 17963, "https");
    
            HttpGet get = new HttpGet(_spHostApi);
    
            HttpResponse response = httpClient.execute(get);
    
            InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8");
            BufferedReader rd = new BufferedReader(reader);
    
            String line = "";
    
            while ((line = rd.readLine()) != null)
                sb.append(line);
    
            httpClient.getConnectionManager().shutdown();
        }
        catch (Exception ex) { sb.append(ex.toString()); }
    

    非常感谢。请提出建议

    1 回复  |  直到 9 年前
        1
  •  0
  •   Nic    9 年前

    我已经更改了代码,现在正在工作。

    工作代码如下:

    private void HttpLogin() {
        // Define Progress Dialog
        ProgressDialog progressDialog = ProgressDialog.show(this, "Verifying", "Loading..", true);
    
        // Variable
        EditText username = (EditText) findViewById(R.id.txtUsername);
        EditText password = (EditText) findViewById(R.id.txtPassword);
        Spinner company = (Spinner)findViewById(R.id.ddlCompany);
        StringBuilder sb = new StringBuilder();
        String title = "";
        CompanyInfo companyInfo = (CompanyInfo)company.getSelectedItem();
        final String user = username.getText() + "";
        final String pass = password.getText() + "";
        final String domain = companyInfo.getCompanyDomain();
        String authorization = domain + "\\" + user + ":" + pass;
    
        TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }
    
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    
            @Override
            public X509Certificate[] getAcceptedIssuers() { return null; }
        };
    
        // Check
        if (user != "" && pass != "" && domain != "") {
    
            // Error Handling
            try {
                // Reset Variable
                sb = new StringBuilder();
                title = "";
    
                // Certificate
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { trustManager }, new SecureRandom());
    
                // Add Socket Factory
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
                // Accept All Host Verifier
                HostnameVerifier allHostValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) { return true; }
                };
                HttpsURLConnection.setDefaultHostnameVerifier(allHostValid);
    
                // Set Urls
                URL url = new URL("https://YourUrlAddess/");
    
                // Open Connection
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod(Constant._REQUEST_METHOD_GET);
                conn.setRequestProperty("Accept", "*/*");
                conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(authorization.getBytes(), Base64.NO_WRAP));
                conn.connect();
    
                // Check
                if (conn.getResponseCode() == 401) {
                    title = "Login Failed";
                    sb.append("Login username or password invalid.");
                    conn.disconnect();
                }
                else if(conn.getResponseCode() == 200)
                {
                    title = "Authorized";
                    sb.append("You have login to SharePoint");
                    conn.disconnect();
    
                    Intent intent = new Intent(this, eLeave_HomeActivity.class);
                    intent.putExtra(_Username, user);
                    startActivity(intent);
                }
                else
                {
                    title = "Unknown Error";
                    sb.append(conn.getResponseCode() + ": " + conn.getResponseMessage());
                }
    
    
            } catch (Exception ex) { sb.append(ex.toString()); }
        }
        else
        {
            title = "Login Failed";
            sb.append("Username or Password or company cannot be empty");
        }
        progressDialog.dismiss();
        AlertMessage(title, sb.toString());
    }