从JAVA到Sharepoint 2013 REST API的BASIC身份验证
问题内容:
Java应用程序需要访问SharePoint 2013 REST API https://msdn.microsoft.com/zh-
cn/library/office/jj860569.aspx
倾向于使用BASIC身份验证:
在网络上有许多使用其余api的示例,但似乎没有一个可以处理身份验证。也许我在这里错过了一些非常简单的事情。
这可以通过POSTMAN手动进行:http ://tech.bool.se/basic-rest-request-sharepoint-using-postman/,
但需要我在浏览器中输入用户名和密码。
我试过实现此:
使用HttpClientBuilder基本身份验证
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
这导致->警告:NTLM身份验证错误:凭据无法用于NTLM身份验证:org.apache.http.auth.UsernamePasswordCredentials
问题答案:
感谢@fateddy能够解决问题:切记将UsernamePasswordCredentials(“ username”,“
password”));换成NTCredentials(,,,);
使用此Maven依赖项:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
对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();
}
}
}
然后您得到:HTTP / 1.1 200 OK