从JAVA到Sharepoint 2013 REST API的BASIC身份验证

Eri*_*ord 8 java rest sharepoint

Java应用程序需要访问SharePoint 2013 REST API https://msdn.microsoft.com/en-us/library/office/jj860569.aspx

更愿意使用BASIC身份验证:

有许多在网络上使用其余api的例子,但似乎都没有处理身份验证.也许我错过了一些非常简单的东西.

这可以通过POSTMAN手动工作:http://tech.bool.se/basic-rest-request-sharepoint-using-postman/ 但要求我在浏览器中输入用户名和密码.

我试过实现这个: HttpClientBuilder基本 使用auth

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这会导致 - >警告:NTLM身份验证错误:凭据不能用于NTLM身份验证:org.apache.http.auth.UsernamePasswordCredentials

Eri*_*ord 9

感谢@fateddy提供的技巧:记得切换出UsernamePasswordCredentials("username","password"));对于NTCredentials(,,,);

使用这个maven依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

对SharePoint的身份验证有效:

import org.apache.http.client.CredentialsProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.auth.NTCredentials;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

public class SharePointClientAuthentication {

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(AuthScope.ANY),
            new NTCredentials("username", "password", "https://hostname", "domain"));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://hostname/_api/web/lists");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

你最终得到:HTTP/1.1 200 OK

  • “主机名”和“域”字段中应该放什么? (3认同)
  • 我必须访问由公司 SAML 验证的共享点。我必须连接到 URL https://xyz.sharepoint.com/teams/x/y/z/AllItems.aspx 并必须从此页面下载文件。您能否建议我如何使用 Java RESTful 客户端应用程序执行此操作?我已经使用上面的代码进行连接并收到 HTTP/1.1 403 Forbidden (2认同)