HowTrying to consume Rest api of Sharepoint from j

2019-08-10 03:43发布

问题:

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

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

回答1:

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