【问题标题】:Downloading files from a given SharePoint folder从给定的 SharePoint 文件夹下载文件
【发布时间】:2016-10-08 11:07:41
【问题描述】:

我创建了一个 Java 客户端,用于从给定的 SharePoint 链接下载文件。首先,我通过我的凭据对 SharePoint 链接进行了身份验证,作为响应,我得到了一个响应对象。

我在上述步骤之后被卡住了。如何下载这些文件。我也尝试过使用JShare,但使用JShare 我收到了401 Unauthorized 错误。

请指导我完成这个。我已经完成了身份验证部分。需要下载这些文件。

【问题讨论】:

    标签: java sharepoint-2013


    【解决方案1】:

    如果您仍然遇到此问题,请首先使用 SharePoint URL、用户名和密码创建服务实例。 这个例子是使用JShare library-

    Service service = new Service("https://your.sharepoint.com", "username", "password");
    

    现在使用-从服务实例获取 InputStream-

    InputStream inputStream = service.getFileStream("/Shared Documents/Test.docx");
    

    获得 InputStream 后,您可以根据需要轻松下载文件。

    这里的棘手部分是 SharePoint URL 和文件路径。如果您在获取服务实例时收到 401 或 403,并且您可以使用相同的凭据访问 Web 上的 SharePoint,那么可能的原因很少

    • 在创建服务实例时检查您的 URL。在您有权访问的项目或文件夹之前,它应该是完整的 URL。例如https://your.sharepoint.com/{项目名称}
    • 外部用户与内部用户:我不知道为什么,但 SharePoint Online 不通过代码对外部用户进行身份验证。 (我在这个问题上停留了很长时间,我在 SharePoint 的一些讨论/论坛中找到了它)

    【讨论】:

      【解决方案2】:

      关于开发使用的信息 - https://paulryan.com.au/2014/spo-remote-authentication-rest/ 那里的一切都得到了很好的描述。

      import java.io.*;
      import java.net.*;
      import javax.xml.parsers.*;
      import javax.xml.xpath.*;
      import org.w3c.dom.Document;
      import org.xml.sax.*;
      
      public class LoginManagerSharePoint {
          private final String sts = "https://login.microsoftonline.com/extSTS.srf";
          private final String loginContextPath = "/_forms/default.aspx?wa=wsignin1.0";
          //private final String contextInfoPath = "/_api/contextinfo";
          private final String sharepointContext = "xxxxxxx";
          private final String reqXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                  "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" " +
                  "xmlns:a=\"http://www.w3.org/2005/08/addressing\" " +
                  "xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
                  "<s:Header><a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" +
                  "</a:Action><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>" +
                  "</a:ReplyTo><a:To s:mustUnderstand=\"1\">https://login.microsoftonline.com/extSTS.srf</a:To>" +
                  "<o:Security s:mustUnderstand=\"1\" " +
                  "xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                  "<o:UsernameToken><o:Username>[username]</o:Username><o:Password>[password]</o:Password>" +
                  "</o:UsernameToken></o:Security></s:Header><s:Body><t:RequestSecurityToken " +
                  "xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">" +
                  "<wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">" +
                  "<a:EndpointReference><a:Address>[endpoint]</a:Address></a:EndpointReference>" +
                  "</wsp:AppliesTo><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey" +
                  "</t:KeyType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue" +
                  "</t:RequestType><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>" +
                  "</t:RequestSecurityToken></s:Body></s:Envelope>";
          private String generateSAML() {
              String saml = reqXML
                      .replace("[username]", "username");
              saml = saml.replace("[password]", "password");
              saml = saml.replace("[endpoint]", String.format("https://%s.sharepoint.com/_forms/default.aspx?wa=wsignin1.0", sharepointContext));
              return saml;
          }
      
          public String getCookie() {
              String token;
              try {
                  token = requestToken();
                  String cookie = submitToken(token);
                  //System.out.println(cookie);
                  return cookie;
              } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return null;
          }
      
          private String requestToken() throws XPathExpressionException, SAXException,
                  ParserConfigurationException, IOException {
      
              String saml = generateSAML();
      
              URL u = new URL(sts);
              URLConnection uc = u.openConnection();
              HttpURLConnection connection = (HttpURLConnection) uc;
      
              connection.setDoOutput(true);
              connection.setDoInput(true);
              connection.setRequestMethod("POST");
              // http://stackoverflow.com/questions/12294274/mobile-app-for-sharepoint/12295224#12295224
              connection.addRequestProperty("Content-Type",
                      "text/xml; charset=utf-8");
      
              OutputStream out = connection.getOutputStream();
              Writer wout = new OutputStreamWriter(out);
              wout.write(saml);
      
              wout.flush();
              wout.close();
      
              InputStream in = connection.getInputStream();
              int c;
              StringBuilder sb = new StringBuilder("");
              while ((c = in.read()) != -1)
                  sb.append((char) (c));
              in.close();
              String result = sb.toString();
              String token = extractToken(result);
              //System.out.println(token);
              return token;
          }
      
          private String extractToken(String result) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
              //http://stackoverflow.com/questions/773012/getting-xml-node-text-value-with-java-dom
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
      
              Document document = db.parse(new InputSource(new StringReader(result)));
      
              XPathFactory xpf = XPathFactory.newInstance();
              XPath xp = xpf.newXPath();
              String token = xp.evaluate("//BinarySecurityToken/text()", document.getDocumentElement());
              //handle error  S:Fault:
              //http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/df862099-d9a1-40a4-b92e-a107af5d4ca2
              //System.out.println(token);
              return token;
          }
      
          private String submitToken(String token) throws IOException {
              // http://cafeconleche.org/books/xmljava/chapters/ch03s05.html
              String url = String.format("https://%s.sharepoint.com%s", sharepointContext, loginContextPath);
              URL u = new URL(url);
              URLConnection uc = u.openConnection();
              HttpURLConnection connection = (HttpURLConnection) uc;
      
              connection.setDoOutput(true);
              connection.setDoInput(true);
              connection.setRequestMethod("POST");
              connection.addRequestProperty("Accept", "application/x-www-form-urlencoded");
              connection.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
              // http://stackoverflow.com/questions/12294274/mobile-app-for-sharepoint/12295224#12295224
              connection.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
      
              connection.setInstanceFollowRedirects(false);
      
              OutputStream out = connection.getOutputStream();
              Writer wout = new OutputStreamWriter(out);
      
              wout.write(token);
      
              wout.flush();
              wout.close();
      
              InputStream in = connection.getInputStream();
      
              //http://www.exampledepot.com/egs/java.net/GetHeaders.html
              String setCookieRtFa = null;
              String setCookieFedAuth = null;
      
              for (int i=0; ; i++) {
                  String headerName = connection.getHeaderFieldKey(i);
                  String headerValue = connection.getHeaderField(i);
                  //System.out.println("header: " + headerName + " : " + headerValue);
                  if (headerName == null && headerValue == null) {
                      // No more headers
                      break;
                  }
                  if (headerName == null) {
                      // The header value contains the server's HTTP version
                  }
      
                  if (headerName != null) {
                      if (headerName.equals("Set-Cookie")) {
                          if (setCookieRtFa == null) {
                              setCookieRtFa = headerValue;
                          } else {
                              int t = 0;
                              if (headerValue.equals("RpsContextCookie=; path=/"))   t = 1;
      
                              if (t == 0) {
                                  setCookieFedAuth = headerValue;
                              }
                          }
                      }
                  }
      
              }
              String cookieContainer = setCookieRtFa.split("\\;")[0] + ";" + setCookieFedAuth.split("\\;")[0];
      
              in.close();
      
              return cookieContainer;
          }
          }
      
              LoginManagerSharePoint loginManagerSharePoint = new LoginManagerSharePoint();
              String cookieContainer = loginManagerSharePoint.getCookie();
      
              HttpClient httpClient = HttpClientBuilder.create().build();
              HttpGet httpGet = new HttpGet(URL_FILE);
              httpGet.addHeader("Cookie", cookieContainer);
              httpGet.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
      
              HttpResponse response = httpClient.execute(httpGet);
              InputStream inputStream = response.getEntity().getContent();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-11
        • 2022-08-05
        • 1970-01-01
        • 2015-09-19
        • 2015-09-04
        • 2020-04-26
        • 1970-01-01
        • 2015-11-09
        相关资源
        最近更新 更多