如何尝试从 Java 客户端使用 Sharepoint 的 Rest api 但获取状态代码 403 Forbidden

如何尝试从 Java 客户端使用 Sharepoint 的 Rest api 但获取状态代码 403 Forbidden

问题描述:

我正在尝试通过 java 客户端使用 Sharepoint 的 rest api 获取文件,但收到 403 Forbidden 错误代码.

I am trying to get files using rest api of Sharepoint through java client, but getting 403 Forbidden error code.

    Client c = Client.create();
    WebResource resource = c.resource("http://URL/_api/web/GetFolderByServerRelativeUrl('/Folder')/Files");     
    String userCredentials = "Username:Password";
    resource.header("Authorization", "Basic " + new String(new Base64().encode(userCredentials.getBytes())));
    resource.header("Accept","application/json; odata=verbose");
    String response = resource.get(String.class);

我在标题中发送授权仍然面临同样的错误.用soap wsdl也尝试了同样的事情,但得到了相同的响应.

I am sending Authorization in header still facing same error. Tried same thing with soap wsdl also but getting same response.

这就是我使用 NTML 进行身份验证的方式 - 技巧是从这个示例更改为 NTCredentials() 与 UsernamePasswordCredentials() ->https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java

This is how I'm authenticating with NTML - trick was to change to NTCredentials() vs UsernamePasswordCredentials() from this example -> https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java

Maven 依赖:org.apache.httpcomponentshttp客户端4.4.1

Maven dependency: org.apache.httpcomponents httpclient 4.4.1

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();
    }
}
}