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

时间:2015-03-26 12:07:07

标签: java rest sharepoint soap

我试图通过java客户端使用Sharepoint的rest api获取文件,但获取403 Forbidden错误代码。

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

我在标题中发送授权仍面临同样的错误。用肥皂wsdl尝试同样的事情,但得到相同的回应。

1 个答案:

答案 0 :(得分:0)

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

Maven依赖:              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();
    }
}
}