Home > SharePoint > Reading a SharePoint list with Java: tutorial

Reading a SharePoint list with Java: tutorial

Using external business data with SharePoint part 2: SharePoint Web Services and Java

In this tutorial I will show how to consume and use a SharePoint Lists Web Service from java with Netbeans. The objective will be to read the items of a SharePoint list from a java application. The functions coded in this tutorial will be needed later on if you’re trying to use external business data with SharePoint (my next post will describe how to the create/update/delete items in a list). Sounds pretty basic? Well, I haven’t found any other tutorials of this kind for Java, so enjoy!

SharePoint Java Application Netbeans Screenshot

Tutorial: reading a list

This tutorial has been tested Netbeans 6.8 and SharePoint Online, however any other Java IDE should be suitable. It should work with MOSS 2007 too (please let me know if it doesn’t). First of all, I’d recommend reading my previous post about the challenges to expect while coding such an application in Java. Before you begin, make sure you have a Sharepoint list that’s populated with a few items.

  1. Get the WSDL. Before launching Netbeans, you’ll need to download the Lists web service WSDL file with your browser to a local directory. The URL to your WSDL should look like: sharepointsite.com/_vti_bin/Lists.asmx?WSDL. The reason why you’ll download the WSDL instead of parsing it remotely from your Netbeans project is because you’ll want to avoid errors at build or run time. I tried with Netbeans 6.5, 6.7, 6.8, and encountered a variety of problems when I tried to access and parse the WSDL remotely (NTLM authentication errors, jaxb parsing errors, WSDL not found errors, etc)… Parsing it locally seems to be the simplest workaround to those Netbeans bugs complexities.
  2. Parse the WSDL. In order to use Sharepoints Web Services with Java, you will need to generate its stub classes with its WSDLs.
    • From Netbeans (easy): Open Netbeans and create a new Java Application. Right-click on your project and create a new Web Service Client, and choose your Lists WSDL file. Choose JAX-WS as Client Style. Click finish and that’s it. To make sure everything’s fine, clean and build your project.
    • From the console : If you’re not using Netbeans, you can generate the stub classes manually from the console, thanks to the JDK wsimport tool. Open the console (cmd.exe) and open the directory where your Lists.wsdl file is located. Run the following command to generate the classes in the directory (change the paths if necessary) “C:\Program Files\Java\jdk1.6.0_12\bin\wsimport.exe” -p com.microsoft.schemas.sharepoint.soap -keep -extension Lists.wsdl. Import those classes in your IDE.

  3. Code the SOAP authentication function. The first coding we’ll do is to create a Manager class that will take care of the Lists Web Service authentication and manipulation. If successful, it will return an open lists port (ListsSoap object) that will offer all the functions we need to use the Lists Web Service. Here’s the authentication function:
  4.     /**
         * Creates a port connected to the SharePoint Web Service given.
         * Authentication is done here. It also prints the authentication details
         * in the console.
         * @param userName SharePoint username
         * @param password SharePoint password
         * @return port ListsSoap port, connected with SharePoint
         * @throws Exception in case of invalid parameters or connection error.
         */
        public static ListsSoap sharePointListsAuth(String userName, String password) throws Exception {
            ListsSoap port = null;
            if (userName != null && password != null) {
                try {
                    Lists service = new Lists();
                    port = service.getListsSoap();
                    System.out.println("Web Service Auth Username: " + userName);
                    ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
                    ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
                } catch (Exception e) {
                    throw new Exception("Error: " + e.toString());
                }
            } else {
                throw new Exception("Couldn't authenticate: Invalid connection details given.");
            }
            return port;
        }
    

    Now that the auth code is made, you may call it from your main class to make sure the connection went fine. This code will display some information in the console in case of error.

  5. Code a function that’ll display XML docs in your console. Most of the time, SharePoint Web Services will return you a huge chunk of information in Microsoft’s own XML / CAML format. This is precisely what we’ll be interested in, as we’ll parse these Web Service responses later to display the lists items for instance. It’s very helpful to have such a function for debugging purposes. We’ll use the old school XML parsing tools embedded in the JDK for that job (javax.xml.transform).
  6.     /**
         * Creates a string from an XML file with start and end indicators
         * @param docToString document to convert
         * @return string of the xml document
         */
        public static String xmlToString(Document docToString) {
            String returnString = "\n-------------- XML START --------------\n";
            try {
                //create string from xml tree
                //Output the XML
                //set up a transformer
                TransformerFactory transfac = TransformerFactory.newInstance();
                Transformer trans;
                trans = transfac.newTransformer();
                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                trans.setOutputProperty(OutputKeys.INDENT, "yes");
                StringWriter sw = new StringWriter();
                StreamResult streamResult = new StreamResult(sw);
                DOMSource source = new DOMSource(docToString);
                trans.transform(source, streamResult);
                String xmlString = sw.toString();
                //print the XML
                returnString = returnString + xmlString;
            } catch (TransformerException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
            returnString = returnString + "-------------- XML END --------------";
            return returnString;
        }
    
  7. Code a function that’ll read your lists items. This function will send a getListItems request to the lists web service using the open ListsSoap port we created before. That’s the easy part! The challenging part is interpreting the dense Soap response, which has that infamous CAML structure. Basically, you have to cast the Web Service response into a classic XML document. That way, you can parse it with your favorite XML reader once you know what you’re looking for.
  8.     /**
         * Connects to a SharePoint Lists Web Service through the given open port,
         * and reads all the elements of the given list. Only the ID and the given
         * attributes (column names) are displayed, as well as a dump of the SOAP
         * response from the Web Service (for debugging purposes).
         * @param port an already authentificated SharePoint Online SOAP port
         * @param listName original name of the Sharepoint list that is going to be read
         * @param listColumnNames arraylist containing the various names of the Columns
         * of the SharePoint list that are going to be read. If the column name isn't
         * found, then an exception will be thrown
         * @param rowLimit limits the number of rows (list items) that are going to
         * be returned
         * @throws Exception
         */
        public static void displaySharePointList(ListsSoap port, String listName, ArrayList<String> listColumnNames, String rowLimit) throws Exception {
            if (port != null && listName != null && listColumnNames != null && rowLimit != null) {
                try {
    
                    //Here are additional parameters that may be set
                    String viewName = "";
                    GetListItems.ViewFields viewFields = null;
                    GetListItems.Query query = null;
                    GetListItems.QueryOptions queryOptions = null;
                    String webID = "";
    
                    //Calling the List Web Service
                    GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);
                    Object listResult = result.getContent().get(0);
                    if ((listResult != null) && (listResult instanceof ElementNSImpl)) {
                        ElementNSImpl node = (ElementNSImpl) listResult;
    
                        //Dumps the retrieved info in the console
                        Document document = node.getOwnerDocument();
                        System.out.println("SharePoint Online Lists Web Service Response:" + Manager.xmlToString(document));
    
                        //selects a list of nodes which have z:row elements
                        NodeList list = node.getElementsByTagName("z:row");
                        System.out.println("=> " + list.getLength() + " results from SharePoint Online");
    
                        //Displaying every result received from SharePoint, with its ID
                        for (int i = 0; i < list.getLength(); i++) {
    
                            //Gets the attributes of the current row/element
                            NamedNodeMap attributes = list.item(i).getAttributes();
                            System.out.println("******** Item ID: " + attributes.getNamedItem("ows_ID").getNodeValue()+" ********");
    
                            //Displays all the attributes of the list item that correspond to the column names given
                            for (String columnName : listColumnNames) {
                                String internalColumnName = "ows_" + columnName;
                                if (attributes.getNamedItem(internalColumnName) != null) {
                                    System.out.println(columnName + ": " + attributes.getNamedItem(internalColumnName).getNodeValue());
                                } else {
                                    throw new Exception("Couldn't find the '" + columnName + "' column in the '" + listName + "' list in SharePoint.\n");
                                }
                            }
                        }
                    } else {
                        throw new Exception(listName + " list response from SharePoint is either null or corrupt\n");
                    }
                } catch (Exception ex) {
                    throw new Exception("Exception. See stacktrace." + ex.toString() + "\n");
                }
            }
        }
    
  9. Test the whole thing!
  10. Everything should be ready. Let’s test it from main (of course replace the necessary values with your own).

        public static void main(String[] args) {
            try {
    
                //Authentication parameters
                String userName = "yourUsername";
                String password = "yourPassword";
    
                //Opening the SOAP port of the Lists Web Service
                ListsSoap port = Manager.sharePointListsAuth(userName, password);
    
                /*
                 * Lists Web service parameters
                 * The list names below must be the *original* names of the list.
                 * if a list or column was renamed from SharePoint afterwards,
                 * these parameters don't change.
                 */
                String listName = "Client";
                String rowLimit = "150";
                ArrayList<String> listColumnNames = new ArrayList<String>();
                listColumnNames.add("Title");
                listColumnNames.add("otherColumnName");
    
                //Displays the lists items in the console
                Manager.displaySharePointList(port, listName, listColumnNames, rowLimit);
            } catch (Exception ex) {
                System.err.println(ex);
            }
        }
    

    This is it!I hope you found this post useful. Any thoughts? I’d be happy to hear your feedback. You can download the full source code covered in this tutorial here.

    Update 26 February 2010: Removed unnecessary web service URL in the authentication code (thanks Claus Fassing!)

  1. February 19, 2010 at 11:56

    Pretty nice tut.
    The auth method does not work for me cause the generated Lists classes already include the WSDL location, but i figure out another way to get basic authentication work.

    @Stateless
    @Local(SharepointService.class)
    public class SharepointServiceBean implements SharepointService {

    public void setAuthentication(String userName, String password) {
    Authenticator.setDefault(new PasswordAuthenticator(userName, password));

    }

    private class PasswordAuthenticator extends Authenticator {
    private String userName;
    private String password;

    public PasswordAuthenticator(String userName, String password) {
    this.userName = userName;
    this.password = password;
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
    return (new PasswordAuthentication(userName, password.toCharArray()));
    }
    }
    }

    I would like to know if it’s possible to get the raw xml as response. From this one i could build an object structure by using JAXB

    At this moment i use the org.w3c.dom Element interface.
    Element itemResultEl = (Element) listItemsResult.getContent().get(0);
    NodeList nodeList = itemResultEl.getElementsByTagName(“z:row”);
    Node node = nodeList.item(0);

    Pretty awesome

    • February 26, 2010 at 19:19

      Nice find Claus.
      It is indeed unnecessary to use the SharePoint Web Service URL in our code here, as it is already present in the WSDL. I’ll update the tutorial accordingly.
      Let me know if you manage to unmarshal the response with JAXB, I’d be very interested.

  2. Peter
    February 23, 2010 at 10:51

    Hi,

    I tried to run the code but I get the following:
    java.lang.ClassCastException: $Proxy11
    it’s an Exception that is thrown in “sharePointListsAuth” method.
    Any ideas?

    • Peter
      February 23, 2010 at 10:57

      OK, I managed to get rid of this Exception but still I get:
      org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
      is this example ok to use with NTLM auth?

      thanks for your help.
      Peter

      • February 23, 2010 at 11:07

        No, this related to basic auth. As far as i know NTLM does not work at all

  3. Peter
    February 23, 2010 at 11:37

    What do you mean by saying “does not work at all”? It’s impossible to get to Sharepoint(NTLM) by using JAVA?

  4. Travis
    March 5, 2010 at 18:27

    I went through this tutorial but I can’t get it to work. It fails with a 401 unauthorized error. It actually doesn’t matter what I put in for the user name password, it can even be blank. I did find that it bails on:

    GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);

    where it actually tries to grab the list. Any ideas, I’m pretty stuck right now and would love to get this working.

    • March 5, 2010 at 18:51

      Have you tried activating the “basic authentication” for your SharePoint site in the IIS settings of your server? That’s what did the trick for Juel, who had a similar problem (check the comments : https://davidsit.wordpress.com/2010/02/23/reading-a-sharepoint-list-with-php ).

    • March 5, 2010 at 21:24

      Do you use a domain log in ?

      Domain has to defined with the username like this.
      String userName = “domain\\username”

      • Travis
        March 5, 2010 at 21:33

        I use a domain login, and that’s the format I used for the user name. I haven’t looked at the sharepoint server yet. I will have to talk to the person in charge of that to see if we can turn on basic auth. If it can’t be enabled for some reason, do I have some other options? Thanks for the help.

  5. Travis
    March 8, 2010 at 18:08

    I am able to wget an rss feed generated by sharepoint, so it seems that basic auth is allowed. It still requires a user name and password, but it gives me a 401 unauthorized error 2 times before actually getting the data for me.

    Resolving sharepoint.server… IP
    Connecting to sharepoint.server|IP|:443… connected.
    HTTP request sent, awaiting response… 401 Unauthorized
    Reusing existing connection to sharepoint.server:443.
    HTTP request sent, awaiting response… 401 Unauthorized
    Reusing existing connection to sharepoint.server:443.
    HTTP request sent, awaiting response… 200 OK

    Then the file transfers like normal.

    I wonder if something similar is going on here. Interestingly, I can add the domain in front of my user name or not with wget. It works that same either way. I’d love to get this working in Java as it opens up a lot more info, but I have a workaround for now. Thanks for you suggestions and help.

  6. Nelly T
    March 16, 2010 at 22:06

    Hi David,
    I get the list with no problem,
    but how do I read (not upload) the content of the document from the Sharepoint?
    the example on MSDN with ByteStream converted into Java data structs , returned “File not found”. do I have to use another web service, and not Lists.asmx? for example, I have a couple of text files, .xls and .jpg in
    my Document Library.
    thank you

    • vel
      August 17, 2010 at 16:37

      hey Nelly T
      I am also getting the 401 transport Unauthorised error. How do you get this working w/o any issues?

      can u attach the java code (not the generated one). i would try your code.
      thanks
      vel

      • September 2, 2010 at 08:59

        Hello,

        You need an anonymous access to the root wsdl on your sharepoint server to open the service port.
        You cannot open the service port with authentication AFAIK, not even basic auth.
        All other targets should use basic authentication. Note, you probably have to change your endpoint address.

        Lists lists = new Lists(new URL(“https://sharepoint.domain.tld/_vti_bin/Lists.asmx?WSDL”), new QName(“http://schemas.microsoft.com/sharepoint/soap/”,
        “Lists”));
        ListsSoap port = lists.getListsSoap();

        This will fail if no anonymous access to the root wsdl is given !

        If your service port established, bind username and password

        ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, “USER”);
        ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, “PASS”);
        // Change the endpoint address to the place where you work on. e.g. testcase list
        ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, “https://sharepoint.domain.tld/testcase/_vti_bin/lists.asmx”);

        HTH Claus

      • Nelly T
        September 2, 2010 at 14:41

        It was long ago, but I had to use “Copy”
        service to get the content, which returns a 64-base bytestream.
        Then, convert it to normal form using Base64 utility, it’s free download.
        But I didn’t get “401 unauthorized”, which leads me to believe you may have not included your domain correctly or
        used domain/domain/user in Http POST.
        check your trace first.

      • Nelly T
        September 2, 2010 at 22:07

        It’s nice to know trick with anonymous access. I used NTLM authentication to open the port, and continued with NTLM. I had a username that was given access to SharePoint directory. Note, I dind’t have to code for NTLM or use options, jax-ws did it for me.

  7. aopp
    April 7, 2010 at 17:12

    Hey David,

    Thank you very much for this blog, very detailed and only useful Java code examples I’ve found.

    I am also having trouble authenticating. Basic authentication is enabled on my server and I’ve tried all combinations of Domain\\Username, username@domain.com, etc…

    I am getting this error message:
    com.sun.xml.internal.ws.client.ClientTransportException: request requires HTTP authentication: Unauthorized

    • aopp
      April 7, 2010 at 19:42

      I was able to get authentication to work, using the Authenticator class. But I think this is a non-ideal solution.

      However, I am now getting this exception on the getListItems() call:

      Exception in thread “main” javax.xml.ws.soap.SOAPFaultException: Server did not recognize the value of HTTP Header SOAPAction: .
      at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:171)
      at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:94)

      • aopp
        April 7, 2010 at 19:52

        Haha. ok, nvm, this was because I forgot to include “-extension” when executed the wsimport command.

        I have now answered my own questions, but will leave these up here in case somebody else runs into similar problems.

      • April 7, 2010 at 20:56

        Hey aopp,
        Good to know you found a solution, thanks for sharing it with us.
        Cheers,
        David

      • Leonid Sokolin
        April 9, 2010 at 22:26

        Hi David and aopp,

        I tried to run this application, but see the following expection as well:

        Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type ‘Microsoft.SharePoint.SoapServer.SoapServerException’ was thrown.

        It happens at GetListItemsResponse.GetListItemsResult call.

        Authentication seems to be working though.

        Any ideas?

        Thanks in advance,

        Leonid

      • Leonid Sokolin
        April 12, 2010 at 22:49

        Hi David,

        I was able to make the code working, but still have one problem.

        I was to get a list of subfolders from the site and according to SP it should be possible to achive by using Folder property of GetListItems.QueryOptions.

        Could you show me the example of how this property could be made non-null in this line of your code?

        GetListItems.QueryOptions queryOptions = null;

        Thanks,

        Leonid

      • aopp
        April 13, 2010 at 21:19

        I am also struggling to do something similar. I am trying to get set ViewAttrbiutes of QueryOptions to RecursiveAll, in the hopes that this parameter will allow me to retrieve a list of Files. But I get a SoapException. My code looks something like this:

        ObjectFactory factory = new ObjectFactory();
        QueryOptions options = factory.createGetListItemsQueryOptions();

        DocumentBuilder docBuilder = null;
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        docBuilder = dbfac.newDocumentBuilder();
        Document rootDocument = docBuilder.newDocument();

        Element viewElement = rootDocument.createElement(“ViewAttributes”);
        viewElement.setAttribute(“Scope”, “RecursiveAll”);

        rootDocument.appendChild(viewElement);

        options.getContent().add(0, rootDocument.getDocumentElement());

        GetListItemsResponse.GetListItemsResult r = getListsSoap().getListItems(id, “”, null, null, “150”, options, null);

      • Leonid Sokolin
        April 14, 2010 at 22:05

        I managed to resolve this problem by using the following code:

        Node elementOptions = generateXmlNode(“Root\\Folder”);
        GetListItems.QueryOptions queryOptions = new GetListItems.QueryOptions();
        queryOptions.getContent().add(elementOptions);

        public static Node generateXmlNode(String sXML) throws ParserConfigurationException,
        SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document documentOptions = builder.parse(new InputSource(new StringReader(sXML)));
        Node elementOptions = documentOptions.getDocumentElement();
        return elementOptions;
        }

        It correctly gets results from SP folder now.

        I have another problem though. Program runs on Windows because it is using NTLM authentication. I need to run it on Unix though and it fails with the following error:

        [java] Web Service Auth Username: domain\username
        [java] Before getting new Lists
        [java] java.lang.Exception: Error: Unable to create StAX reader or writer
        [java] at com.nb.ws.client.SharePointTools.sharePointListsAuth(SharePointTools.java:58
        [java] at com.nb.ws.client.SharepointClient.main(SharepointClient.java:17)

        It is interesting that exception is thrown immediately after Lists service is instantiated:

        System.out.println(“Before getting new Lists”);
        Lists service = new Lists();
        System.out.println(“Before getListsSoap”);
        port = service.getListsSoap();
        ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
        ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

        So, username/password are not even used yet.

        Apparently, this happens because it can’t authenticate from Unix using NTLM.
        Also, my SP site has basis authentication disabled.

        Any suggestions?

      • Ethan
        April 21, 2010 at 07:45

        Hi, Leonid,
        I had the same issue where the client code works fine on Windows, but failed when using it in on Linux. Since I didn’t have other choice, I decided to try the other way using Axis library: http://derekjmiller.spaces.live.com/blog/cns!A77124B9D0EE317F!142.entry
        Turns out it works for me !! Hope this helps.

      • January 2, 2017 at 11:22

        hi aopp,

        Even I am getting below exception
        java.lang.Exception: Exception. See stacktrace.com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized

        Can you please suggest how to debug this problem, I am using authenticator with domain\username and password. still getting the same problem. any suggestion please

  8. aopp
    April 9, 2010 at 19:50

    Hey David,

    I’m trying to use this code to retrieve a list of all documents/folders in my documents library. I populated the library with a folder and a document. When I use this code:

    GetListItemsResponse.GetListItemsResult result = getListsSoap().getListItems(“Documents”, “”, null, null, “150”, null, “”);

    result does not seem to contain anything of interest. just a couple of empty lists and nodes. nothing resembling a representation document or folder.

    any helpful advice?

    • eldar
      January 27, 2012 at 01:45

      aopp i’m getting the same error how did you fix it?

  9. Xia
    April 15, 2010 at 05:31

    Xia :
    I actually just

    Xia :
    Hello David,
    Very good post, thanks for it. I just did something following your instruction. It’s really helpful.
    I’ve got a question though, why when I did the list, Sharepoint only return part of the entries? Is that because the “query” was set to null and it returned entries according to its “Default” criteria? One notable difference is none entries which “start date” over 1 month later is returned..
    So do you have some experience / example for the Query setting in Java -> SharePoint? Can you share with us for a bit?
    Really appreciate.
    -Xia

    I just found the solution. Just to reuse Leonid’s code, it’s actually easy. I must have some syntax error before.
    One simple example is:
    GetListItems.Query query = new GetListItems.Query();
    query.getContent().add(generateXmlNode(
    “” +
    “” +
    “” +
    “” +
    “0″ +
    “” +
    “” +
    “”
    ));
    Then put it to the Query, Done
    Thank you David anyway for this place, so ppl can discuss this very specific topic. It’s kind of weird we connect to SharePoint with Java instead of .NET. But sometimes this kind of thing always happens. Like my current situation, we must read data from another department’s system(SP) in our program (Java). Painful.

    Ooops.

    query.getContent().add(generateXmlNode(
    “<Query>” +
    “<Where>” +
    “<Gt>” +
    “<FieldRef Name=’ID’ />” +
    “<Value Type=’Number’>0</Value>” +
    “</Gt>” +
    “</Where>” +
    “</Query>”
    ));

    • chi
      November 24, 2011 at 16:54

      Just a quick note on this to ensure you use the correct import statement for Node.

      import org.w3c.dom.Node;

      I used Leonid’s example above with the code below to obtain recursive subfolders:

      Node elementOptions = generateXmlNode(“” +
      “”+
      “”
      );

  10. aopp
    April 15, 2010 at 16:19

    Leonid,

    I am getting the below exception on the builder.parse(…) line of your code.

    org.xml.sax.SAXParseException: Document root element is missing.

    • aopp
      April 15, 2010 at 16:26

      aopp :
      Leonid,
      I am getting the below exception on the builder.parse(…) line of your code.
      org.xml.sax.SAXParseException: Document root element is missing.

      ok, nevermind, if i make the generateXmlNode with some xml-ish string, like, generateXmlNode(“”+folderName+””);, the I don’t get the SAXParseException. But I do still get the soapException when I try to add this element to my queryOptions. Any suggestions?

  11. Jordi Anguela
    April 20, 2010 at 15:44

    Thank you David for this tutorial. It is really hard to find examples in Java to work with Sharepoint.
    I’m currently working in a integration between Bonita Open Solution and Sharepoint and your tutorial helped me a lot.

  12. Kasi
    May 4, 2010 at 13:08

    Hey David, i managed to get data from sharepoint by webservice because of this tutorial, thank you for that. now, my question is how to get fields that i create in our sharepoint list on my own. in c# you can get that by making a xml Element and with a list of that fields. I don´t understand how to give viewField (GetListItems.ViewFields) my additional fields like x_NEW_FIELD_FOR_SECRET_NUM, can you give me an advice? is there another way to get these new fields?

    Thanks!

    • Yu
      September 10, 2010 at 15:54

      Kasi,
      Have you found out how to set viewField?
      Please share if you do. I’m searching it online but couldn’t find an example. Many many thanks!

  13. Marc de Klerk
    May 17, 2010 at 14:41

    Leonid Sokolin :
    Hi David,
    I was able to make the code working, but still have one problem.
    I was to get a list of subfolders from the site and according to SP it should be possible to achive by using Folder property of GetListItems.QueryOptions.
    Could you show me the example of how this property could be made non-null in this line of your code?
    GetListItems.QueryOptions queryOptions = null;
    Thanks,
    Leonid

    Hey Leonid,

    I’m getting the same exception thrown as you…
    How’d you fix the problem?

    Thanks in advance 😉

  14. Yu
    June 9, 2010 at 20:50

    Thank you, David, Leonid Sokolin and Xia.
    Working for me!

  15. vel
    August 18, 2010 at 16:37

    Hi David

    I tried this tutorial. It does not work for me. I use eclipse. I used JDK 1.6, ran wsimport.exe as you mentioned and then imported the java classes into eclipse. Eclipse re-compiles it.
    when I ran it using JDK 1.5 I get the following error;
    java.lang.Exception: Exception. See stacktrace.javax.xml.ws.WebServiceException: org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized

    then I changed the JDK to 1.6
    Now I am getting the following.
    java.lang.Exception: Exception. See stacktrace.java.lang.NullPointerException

    Since I got NPE, i tried replacing the nulls of objects like view, query with not null objects (just created the object using new.). Now also I am getting the same error.

    Can you please let me know the possible correction.

    I tried my exact outlook AD user ID and password. it does not work.

    Regards
    Vel

    • vel
      August 18, 2010 at 16:41

      hi david,
      sorry – forgot to mention that i am using axis2-1.5.1 version jars other than jdk1.6.
      hope this piece of info helps you in resolving the problem.
      regards
      vel

  16. September 2, 2010 at 22:14

    Nelly T :
    It’s nice to know trick with anonymous access. I used NTLM authentication to open the port, and continued with NTLM. I had a username that was given access to SharePoint directory. Note, I dind’t have to code for NTLM or use options, jax-ws did it for me.

    Hello Nelly,

    how do you bind the user to open port with authentication ?

    Regards Claus

  17. Ori
    September 13, 2010 at 14:57

    Hi David and Claus,

    I tried to read all the posts but could not understand if NTLM authentication is possible or not. I cannot use the basic authentication.

    In addition I do not want the generated WSDL code to contain the host, because my application gets the host as a parameter.

    Can you help?

    Thanks!

    • September 22, 2010 at 09:20

      Hi Ori,

      you can override the endpoint address by using BindingProvider
      ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, getEndpointAddress());

      My getEndpointAddress() fetch the address from properties.

      Regards Claus

  18. Sunu
    October 12, 2010 at 01:10

    Hi David,

    I have been trying to follow the example here to access sharepoint web service from java.

    I am stuck at 2 places as below :

    (1) The below line does not compile for me as Lists is an interface

    Lists service = new Lists();
    I changed that to

    Lists service = new ListsLocator();

    The BindingProvider line gives me class cast exception as below :
    com.microsoft.schemas.sharepoint.soap.ListsSoapStub cannot be cast to javax.xml.ws.BindingProvider

    I appreciate any help in this regard.

    Thank You for the post. Hope to get things working with your help.
    Sunu

    • Derek
      October 22, 2010 at 16:21

      Hi Sunu,

      I had the same issue as you. I am using Eclipse and had used it to parse the WSDL. Then I used the console to parse the WSDL instead, as described in Step 2 above. It parsed it differently and then the program worked! Try it!

      Good luck,
      Derek

  19. Derek
    October 20, 2010 at 20:42

    Sunu :Hi David,
    I have been trying to follow the example here to access sharepoint web service from java.
    I am stuck at 2 places as below :
    (1) The below line does not compile for me as Lists is an interface
    Lists service = new Lists();I changed that to
    Lists service = new ListsLocator();
    The BindingProvider line gives me class cast exception as below :com.microsoft.schemas.sharepoint.soap.ListsSoapStub cannot be cast to javax.xml.ws.BindingProvider
    I appreciate any help in this regard.
    Thank You for the post. Hope to get things working with your help.Sunu

    I’m in the exact same boat. Is there another way to pass auth?

  20. RPatton
    November 1, 2010 at 18:17

    I believe that I was able to get this working with Kerberos by using example code from here:

    http://download.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html

    However, I now get the following error:

    java.lang.Exception: Exception. See stacktrace.com.sun.xml.internal.ws.server.UnsupportedMediaException: Unsupported Content-Type: text/html; charset=utf-8 Supported ones are: [text/xml]

    Any help would be greatly appreciated.

    • Nelly T
      November 2, 2010 at 15:24

      RPatton,
      I remember two errors; it was loong time ago, can’t remember which, so try these:
      1. Connection error.
      2. Check network trace: does it show domain name twice? like “irc\irc\username”?
      3. Check if the shareport Url, or sharePointWebServiceUrl var in my code, points
      to the right place. It should be of a form: http://yourmossserver:43192/_vti_bin/Lists.asmx – get this from your generated Lists code, ListsSoap. This is ENDPOINT_ADDRESS_PROPERTY.

  21. Mayank
    November 2, 2010 at 19:43

    I have to access the picture library and am requird to make changes (add/edit/delete) the images, I would be thankful if anyone can provide me the Imaging webservice client implementation.

  22. CaMiX
    December 1, 2010 at 21:26

    Great post. I’m new to MS SharePoint and IIS so it took me awhile to try and figure out how the hell you enable Basic auth. I’ve tried enabling Basic auth everywhere I could find it (IIS, SharePoint Auth Provider). The place that I found that finally got it working was under the IIS “SharePoint Central Administration v3” site. I clicked on the Authentication icon and enabled Basic authentication there. I was then able to utilized the Web Services (especially search.asmx) via the article’s Java instructions. I don’t know what hell the point of the Authentication Providers are in SharePoint but it has just confused the hell out of me.

  23. Anubhav
    December 29, 2010 at 06:08

    Hi all,

    David, thanks for such a great post.
    I am stuck with the following error :
    java.lang.ClassCastException: $Proxy11 cannot be cast to org.apache.axis2.jaxws.BindingProvider

    Peter above mentions in his reply to his post of feb 23,2010 that he managed to resolve the exception. Peter can you please help me with this. If someone else has got a solutions for this, please help.

    • Anubhav
      January 3, 2011 at 07:09

      Hi,

      Managed to run it. The solution is that we have to use javax.xml.ws.BindingProvider instead of the bindingprovider provided with axis2 🙂

  24. webbeginner
    February 14, 2011 at 11:47

    i got following error when i ran yur program for my sharepoint site

    stacktrace.javax.xml.ws.soap.SOAPFaultException,can any body have pointer on this??

    • Peeths
      September 7, 2011 at 06:21

      I am also searching for the solution on this, this is the error message that I am getting

      java.lang.Exception: Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type ‘Microsoft.SharePoint.SoapServer.SoapServerException’ was thrown.

      Can some one help on this

      • Lupita
        November 26, 2011 at 04:48

        I had the same issue, that was because I was searching for a list with the name Client (listName in the example), wich obviously does not exist on your sharepoint server, change the name for a list name you do have on your server, try with Contacts for example.

  25. Artem
    March 31, 2011 at 13:57

    Hello,

    I try to work with the tutorial and I have the next exception during the
    “port = service.getListsSoap();”

    java.lang.Exception: Error: javax.xml.ws.WebServiceException: class com.microsoft.schemas.sharepoint.soap.GetListItems do not have a property of the name {http://schemas.microsoft.com/sharepoint/soap/}listName

    Have you any ideas?
    Thanks!

    • Alex
      January 17, 2013 at 21:27

      Hi, I’m having the same problem.
      Has anyone else faced it? Not sure what’s wrong, the generated classes seem to be fine, at least GetListItems class contains the listName field.

    • Alex
      January 17, 2013 at 22:02

      Just tried creating a port for People Web service located at http://site.com/_vti_bin/people.asmx?wsdl

      I’m getting the similar error:
      java.lang.Exception: Error: javax.xml.ws.WebServiceException: class com.microsoft.schemas.sharepoint.soap.ResolvePrincipals do not have a property of the name {http://schemas.microsoft.com/sharepoint/soap/}principalType

      When I inspected the ResolvePrincipals class, I found the fields:

      @XmlRootElement(name = “ResolvePrincipals”)
      public class ResolvePrincipals {

      protected ArrayOfString principalKeys;
      @XmlList
      @XmlElement(required = true)
      protected List principalType;
      protected boolean addToUserInfoList;

      I have no idea what causes this.

  26. Paul Zimmerman
    June 2, 2011 at 21:53

    Hi,

    What are your thoughts on integrating java and sharepoint workflows? Is it feasible in your opinion?

  27. June 8, 2011 at 16:01

    Hi David,
    I’m getting some errors in parsing point. Like this:

    parsing WSDL…

    [WARNING] src-resolve: Cannot resolve the name ‘s1:guid’ to a(n) ‘type definition’ component.
    line 84 of file:/C:/Users/Miguel%20Alvares/Documents/NetBeansProjects/SharePoint/xml-resources/web-service-references/lists/wsdl/lists.asmx.wsdl#types?schema1

    [WARNING] SOAP port “ListsSoap12”: uses a non-standard SOAP 1.2 binding.
    line 1761 of file:/C:/Users/Miguel%20Alvares/Documents/NetBeansProjects/SharePoint/xml-resources/web-service-references/lists/wsdl/lists.asmx.wsdl

    [console log edited out, too long]

    54 errors
    compilation failed, errors should have been reported
    C:\Users\Miguel Alvares\Documents\NetBeansProjects\SharePoint\nbproject\jaxws-build.xml:24: wsimport failed
    BUILD FAILED (total time: 3 seconds)

  28. June 8, 2011 at 16:08

    Carlos Alvares :
    Hi David,
    I’m getting some errors in parsing point. Like this:
    parsing WSDL…
    [WARNING] src-resolve: Cannot resolve the name ‘s1:guid’ to a(n) ‘type definition’ component.
    line 84 of file:/C:/Users/Miguel%20Alvares/Documents/NetBeansProjects/SharePoint/xml-resources/web-service-references/lists/wsdl/lists.asmx.wsdl#types?schema1
    [WARNING] SOAP port “ListsSoap12″: uses a non-standard SOAP 1.2 binding.
    line 1761 of file:/C:/Users/Miguel%20Alvares/Documents/NetBeansProjects/SharePoint/xml-resources/web-service-references/lists/wsdl/lists.asmx.wsdl
    generating code…
    Lists\AddAttachment.java
    Lists\AddAttachmentResponse.java
    Lists\AddDiscussionBoardItem.java
    Lists\AddDiscussionBoardItemResponse.java
    (..)
    compiling code…
    javac -d C:\Users\Miguel Alvares\Documents\NetBeansProjects\SharePoint\build\generated\jax-wsCache\lists -classpath C:\Program Files (x86)\Java\jdk1.6.0_23\lib\dt.jar;C:\Program Files (..)
    C:\Users\Miguel Alvares\Documents\NetBeansProjects\SharePoint\build\generated\jax-wsCache\lists\Lists\ListsSoap.java:36: cannot find symbol
    symbol : class GetListResponse
    location: class Lists.Lists
    public Lists.GetListResponse.GetListResult getList(

    BUILD FAILED (total time: 3 seconds)

    Any help??

  29. SR
    June 9, 2011 at 02:41

    Just another contribution for the community

    Downloading Latest Version of a document from SharePoint Document Library using SharePoint Web Services and Java.
    ———————————————————————————————————————————–

    Following the above code, I am copy/pasting the working code just for contributing for the commuinty. This code was developed as POC so no gurantee of having no errors.

    public static void main(String[] args) {
    try {
    DownloadDocumentVersionsFromSPDocumentLibrary();
    } catch (Exception ex) {
    System.err.println(ex);
    }
    }

    /**
    01 * Authenticate on SharePoint Server
    02 * @param userName is username for accessing the SharePoint
    03 * @param password is password for accessing the SharePoint
    04 * @return ListsSoap
    05 */
    public static VersionsSoap sharePointVersionsAuth(String userName, String password) throws Exception {
    VersionsSoap port = null;

    if (userName != null && password != null) {
    try {
    Versions service = new Versions();
    port = service.getVersionsSoap();
    System.out.println(“Web Service Auth Username: ” + userName);
    ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
    ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
    } catch (Exception e) {
    throw new Exception(“Error: ” + e.toString());
    }
    } else {
    throw new Exception(“Couldn’t authenticate: Invalid connection details given.”);
    }
    return port;
    }

    /**
    01 * Authenticate on SharePoint Server
    02 * @param userName is username for accessing the SharePoint
    03 * @param password is password for accessing the SharePoint
    04 * @return ListsSoap
    05 */
    public static CopySoap sharePointCopyWebServiceAuth(String userName, String password) throws Exception {
    CopySoap port = null;

    if (userName != null && password != null) {
    try {
    Copy service = new Copy();
    port = service.getCopySoap();
    System.out.println(“Web Service Auth Username: ” + userName);
    ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
    ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
    } catch (Exception e) {
    throw new Exception(“Error: ” + e.toString());
    }
    } else {
    throw new Exception(“Couldn’t authenticate: Invalid connection details given.”);
    }
    return port;
    }

    /**
    02 * Creates a string from an XML file with start and end indicators
    03 * @param docToString document to convert
    04 * @return string of the xml document
    05 */
    public static String xmlToString(Document docToString) {
    String returnString = “\n————– XML START ————–\n”;
    try {
    //create string from xml tree
    //Output the XML
    //set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;
    trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, “yes”);
    trans.setOutputProperty(OutputKeys.INDENT, “yes”);
    StringWriter sw = new StringWriter();
    StreamResult streamResult = new StreamResult(sw);
    DOMSource source = new DOMSource(docToString);
    trans.transform(source, streamResult);
    String xmlString = sw.toString();
    //print the XML
    returnString = returnString + xmlString;
    } catch (TransformerException ex) {
    Logger.getLogger(SPWS.class.getName()).log(Level.SEVERE, null, ex);
    }
    returnString = returnString + “————– XML END ————–“;

    return returnString;
    }

    /**
    *
    */
    public static void DownloadDocumentVersionsFromSPDocumentLibrary() throws Exception {
    VersionsSoap port = null;
    try {

    String userName = “xx”;
    String password = “xxx”;
    //Opening the SOAP port of the Versions Web Service
    port = sharePointVersionsAuth(userName, password);

    GetVersionsResponse.GetVersionsResult result = DocumentLibrary.VersionsGetVersions(port, “http:///Shared%20Documents/Test.docx”);
    Object listResult = result.getContent().get(0);
    if ((listResult != null) && (listResult instanceof ElementNSImpl)) {
    ElementNSImpl node = (ElementNSImpl) listResult;

    //Dumps the retrieved info in the console
    Document document = node.getOwnerDocument();
    System.out.println(“SharePoint Online Lists Web Service Response:” + xmlToString(document));

    //selects a list of nodes which have z:row elements
    NodeList list = node.getElementsByTagName(“result”);//(“z:row”);
    System.out.println(“=> ” + list.getLength() + ” results from SharePoint Online”);

    //Displaying every result received from SharePoint
    for (int i = 0; i < list.getLength(); i++) {

    //Gets the attributes of the current row/element
    NamedNodeMap attributes = list.item(i).getAttributes();
    String ver = attributes.getNamedItem("version").getNodeValue();
    //Download Latest Version only
    if (ver.indexOf("@") != -1) {
    System.out.println("******** Url: " + attributes.getNamedItem("url").getNodeValue() + " ********");
    //Download File on Local Hard Disk using Copy Web Service
    DownloadFileUsingCopyWebService(attributes.getNamedItem("url").getNodeValue(), "C:\\work\\TestSPFileDownloadUsingJava", attributes.getNamedItem("version").getNodeValue());
    }
    }
    } else {
    throw new Exception("List response from SharePoint is either null or corrupt\n");
    }

    } catch (Exception e) {
    throw new Exception("Error: " + e.toString());
    }
    }

    /**
    *
    * @param sourceUrl
    * @param destination
    * @param versionNumber
    * @throws Exception
    */
    public static void DownloadFileUsingCopyWebService(String sourceUrl, String destination, String versionNumber) throws Exception {
    CopySoap port = null;
    try {

    String userName = "sohailr";
    String password = "AliMehdi47";
    //Opening the SOAP port of the Versions Web Service
    port = sharePointCopyWebServiceAuth(userName, password);

    //Extract the filename from the source URL
    String fileName = sourceUrl.substring(sourceUrl.lastIndexOf("/") + 1);

    if (versionNumber != null) {
    fileName = versionNumber + "-" + fileName;
    }
    destination = destination + "\\" + fileName;

    //Prepare the Parameters required for the method
    javax.xml.ws.Holder fieldInfoArray = new javax.xml.ws.Holder();
    javax.xml.ws.Holder cResultArray = new javax.xml.ws.Holder();
    javax.xml.ws.Holder fileContents = new javax.xml.ws.Holder(); // no need to initialize the GetItem takes care of that.

    //Cal Web Service Method
    port.getItem(sourceUrl, cResultArray, fieldInfoArray, fileContents);

    //Write the byte[] to the output file
    FileOutputStream fos = new FileOutputStream(destination);
    fos.write(fileContents.value);
    fos.close();
    } catch (FileNotFoundException ex) {
    System.out.println(“FileNotFoundException : ” + ex);
    } catch (IOException ioe) {
    System.out.println(“IOException : ” + ioe);
    } catch (Exception ex) {
    throw new Exception(“Error: ” + ex.toString());
    }
    }

    Helper Class
    ===========

    import com.microsoft.schemas.sharepoint.soap.GetListItems;
    import com.microsoft.schemas.sharepoint.soap.GetVersionsResponse;
    import com.microsoft.schemas.sharepoint.soap.Lists;
    import com.microsoft.schemas.sharepoint.soap.Versions;
    import com.microsoft.schemas.sharepoint.soap.VersionsSoap;
    import java.io.StringReader;

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    public class DocumentLibrary {

    ///
    /// Constructor
    ///
    public DocumentLibrary() {
    }

    public static GetVersionsResponse.GetVersionsResult VersionsGetVersions(VersionsSoap port, String FileName) throws Exception
    {
    try {
    GetVersionsResponse.GetVersionsResult Result = port.getVersions(FileName);
    return Result;
    } catch (Exception e) {
    throw new Exception(“Error: ” + e.toString());
    }
    }
    }

  30. Shawn
    June 15, 2011 at 19:47

    I am trying to use Eclipse to generate my WS client and running into problems. There are many options when configuring the WSDL 2 Java process as well as many WS implementations, AXIS 1 or 2 or JAX-WS, etc. I eventually settled on Apache CXF which is supposed to be JAX-WS compatible. I was able to generate my Java client and authenticate. But when I try to make a Query, I get an exception complaining about protocol or something. If I replace my Java client with one generated from NetBeans everything works fine. So there must be a difference between how NetBeans generates its Java client versus Eclipse with Apache CXF. Anybody have any suggestions? Should I use Axis 1 or 2 or change some of the options for CXF??

  31. August 18, 2011 at 13:44

    Thanks so much for sharing your knowledge!! This tutorial = awesome! My corporate sharepoint site @ work uses NTLM authentication. I too was receiving the dreaded “401 unauthorized error”. After some persistent Googling, I found this solution here http://goo.gl/u8S44 . I was able to use the java.net.Authenticator class in my own version of an NTLMAuthenticator class. Once I entered my “domain\\username” & password, I was easily able to access my corporate site’s SharePoint lists via the web service operations! I’m off to experiment some more!!

  32. Peeths
    September 7, 2011 at 06:22

    Any Idea on

    java.lang.Exception: Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type ‘Microsoft.SharePoint.SoapServer.SoapServerException’ was thrown.

    ????

  33. MKS
    September 13, 2011 at 17:14

    Cud some one please suggest where would i get the jars for ListsSoap class

  34. Nelly T
    September 13, 2011 at 20:28

    Your question is little bit out of context, but you either include the whole generated tree into your project as a package, – usual, – or if you have it in another project, create jar in Eclipse and copy to where you need them.

  35. kk
    September 14, 2011 at 07:58

    Allways it throws this Exception:
    “Web Service Auth Username: anyName
    java.lang.Exception: Exception. See stacktrace.javax.xml.ws.WebServiceException: java.io.IOException: Authentication failure”
    It fails at:
    “GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);”

    What should I do?

    I dont know which authentication method the server is using, because i dont have permission to see that.

  36. MKS
    September 16, 2011 at 08:42

    Thanks for your response. I got all the classes. I am still facing some issue. I am using eclipse IDE. Its not able to find the class “ElementNSImpl”. Plz help.

  37. Badshah
    September 23, 2011 at 20:52

    Getting compile time issue at
    GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName,
    query, viewFields, rowLimit, queryOptions, webID);

    Error is
    Error(120,70): getListItems(com.microsoft.schemas.sharepoint.soap.GetListItems) in gt.sharepoint.services.ListsSoap cannot be applied to (java.lang.String,java.lang.String,com.microsoft.schemas.sharepoint.soap.GetListItems.Query,com.microsoft.schemas.sharepoint.soap.GetListItems.ViewFields,java.lang.String,com.microsoft.schemas.sharepoint.soap.GetListItems.QueryOptions,java.lang.String)

  38. Jim Hammersmith
    October 15, 2011 at 02:04

    Nice article and thanks for sharing your knowledge. If I have to list the items or documents for a user user1 and if I do not have the password for the user is there a way to accomplish this using? I have the administrator username and password though.

  39. Rubén Padilla
    October 20, 2011 at 00:58

    Hello, which one was the solution for the “Microsoft.SharePoint.SoapServer.SoapServerException” i have seen it posted on this thread like it happened to 3 people but no answer.

    Thank you in advance.

    • chi
      November 23, 2011 at 18:18

      “Microsoft.SharePoint.SoapServer.SoapServerException”

      Make sure that listName = an actual list name. it might not be “Client”

  40. cez
    November 25, 2011 at 15:25

    Hi!

    When I try to connect with SharePoint Online in the Office 365 cloud i get the following exception: Exception in thread “main” com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 301: Moved Permanently. Do you know something about it? It apperes when I run the getListItems method. A answer would be great.#

    Thanks!

  41. udoline
    December 7, 2011 at 15:04
  42. Diego Moreno
    January 4, 2012 at 20:07

    Only a remark:

    The rowLimit cannot be null. If it is defined as null, the Web Service limits the result in 100 registers.

  43. Vinz
    January 25, 2012 at 01:15

    I found some questions about authentication.
    If someone gets a HTTP 401 status code, you most likely have to turn on Basic Authentication on IIS.
    Here is a link how to do that: http://technet.microsoft.com/en-us/library/gg576953.aspx
    HTH

  44. Gorets
    January 26, 2012 at 09:01

    I’ve problem, when I try to load a sharepoint list, I should know a row names in my view. Its not good =), because I need different data.

  45. Anonymous
    February 14, 2012 at 21:04

    Where can I download the source code ?

  46. Rajeev
    February 17, 2012 at 06:50

    Hi David, Using the above example, I tried this to read SharePoint (Active Directory) Lists from Unix, but is throwing the below error. Will the above code works in invoking active directory single-sign-on SharePoint servcices? I tried passing domain name (domain\\username) as well, but still the same error. Also, please can you provide the complete source code, if you have, as the link given is no more working. I’m not a java expert, so your help is really appreciated.

    java.lang.Exception: Exception. See stacktrace.com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized

  47. Srikrishna Krishnaswamy Narasimhan
    February 22, 2012 at 20:16

    the same code does not work for office 365 – sharepoint online/ authentication . any reason ? it says 403 forbidden, unable to send via post to url

    • RamaKrishna Arumalla
      July 25, 2012 at 09:10

      did you resolved the Issue, i am also facing the same Issue 403 forbidden

  48. yaroze
    March 1, 2012 at 16:32

    Thank you VERY much for taking your time writing this tutorial!!

    Too bad that megaupload went down… 😦

    Can you post the source code somewhere else?

    Cheerz,
    Pedro

  49. March 12, 2012 at 13:37

    Hello Everyone,

    I am quite new to WebServices and Sharepoint. I do have a good knowledge of J2EE technologies. I was able to run the code given in this post. But my question is:
    If I want to access a different SharePoint site then do I have to rebuild the application again with the new URL (of WSDL)? Or is there any technique with which I can use the above code for any SharePoint URL (of WSDL)?

    Thanks,
    Mubin

  50. March 19, 2012 at 15:28

    Hello everyone,

    I was able to use the above example with Basic Authentication. I have few questions and I will be very thankful if I can get a reply to those:
    1) How do I get the data type of the column in the list?
    2) How do I find the sequence of the columns in the Sharepoint?

    Thanks,
    Mubin

  51. Selena Ten
    March 22, 2012 at 12:37

    Nelly T :
    It’s nice to know trick with anonymous access. I used NTLM authentication to open the port, and continued with NTLM. I had a username that was given access to SharePoint directory. Note, I dind’t have to code for NTLM or use options, jax-ws did it for me.

    How you do it? Can you give show me some sample code?

  52. SS
    April 27, 2012 at 11:34

    I am able to connect to sharepoint service from my local machine but as I move to our development server, I get ServiceConstructionException : Failed to create service.

    I created the client from wsdl using RSA and then exported it as jar . Then I put this client jar in the lib of application war and then trying to call the webservice.

    What could cause this issue. Please suggest.

  53. sach
    August 22, 2012 at 13:33

    java.net.MalformedURLException: /WEB-INF/wsdl/Lists.wsdl does not exist in the module.
    at com.microsoft.schemas.sharepoint.soap.Lists.(Lists.java:27)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:200)

    wats this ??

  54. September 7, 2012 at 19:30

    I’m getting a compile time error on this line;

    Lists service = new Lists();

    The Lists class does not have a constructor! I compiled against the WSDL using eclipse web client.
    Lists is just an interface!

    • September 20, 2012 at 17:42

      This was answered by post #44. Now I’m getting a 401 because we have domain auth turned on and I don’t have access to the WSDL. I tried creating an NTLM Authenticator class but now that causes a fatal java error! How is anyone getting this to work?

      • Nelly T
        September 20, 2012 at 20:08

        Check my comments #16, #40, #47. Do not include domain in user name. Give your user permission on a Shareport. NTLM works “behind the scenes” in jax-ws, no need to code. It’s possible you’re overwriting the work of what jax-ws does, just because you coded for NTLM.

  55. Ramaraj Ramasamy
    September 21, 2012 at 13:43

    Great article. It works perfectly for me. 🙂 Thanks a lot!!

    • Senthilkumar.A.M
      September 25, 2012 at 08:49

      Hi, Could any one of you pls send me the full code.

  56. mleejr
    October 1, 2012 at 22:17

    Ok. How in the world can this work? In most real world scenario you never know where your final web services will sit so you make the endpoint variable. You do not handle this. I keep getting a 401 or NTLM doesnt want credentials or if I set the Endpoint I get the error: java.lang.Exception: Error: javax.xml.ws.soap.SOAPFaultException: org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found definitions
    at com.exxova.mybi.SharepointService.sharePointListsAuth(SharepointService.java:219)

    This should NOT be this hard. Just basic auth on Sharepoint. When I try to create an NTLMAuthencator class I get a fatal java core.

    Here’s the code;

    Lists service = new Lists();
    listsSoap = service.getListsSoap();
    System.out.println(“Web Service Auth Username: ” + userName);
    ((BindingProvider) listsSoap).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
    ((BindingProvider) listsSoap).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
    ((BindingProvider) listsSoap).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlLocation.toString());
    GetListCollectionResult result = listsSoap.getListCollection();

  57. mleejr
    October 1, 2012 at 22:19

    Nelly T :
    Check my comments #16, #40, #47. Do not include domain in user name. Give your user permission on a Shareport. NTLM works “behind the scenes” in jax-ws, no need to code. It’s possible you’re overwriting the work of what jax-ws does, just because you coded for NTLM.

    Thank you so much for your response. If I am not logged into the domain how do I do NTLM? Or, how can I do basic auth? Or if I am logged into the domain, what is the proper way I should be telling it what server to hit? I had to generate the code from the WSDL on the file system. It kept asking me to log in to view the WSDL so I logged in and copied it locally and generated the code. If I don’t set the endpoint the endpoint is that file. I want it to be a variable endpoint anyway.

  58. mleejr
    October 1, 2012 at 22:23

    Also, I can’t use eclipse to generate anything. Got it. I did it by the command line. Problem is, I can’t just use jax-ws (jdk16 ws right?) because I get errors that I don’t get when I import all the axis2 stuff. I shouldn’t have to import axis2 with jdk16 should I?

  59. Kapil
    November 1, 2012 at 18:18

    Hi Leonid,

    Thanks for the code snippet for subfolders using QueryOptions. However I am running into following SAXParseException issue .
    [Fatal Error] :1:1: Content is not allowed in prolog.
    Its throwing error on this line
    Document documentOptions = builder.parse(new InputSource(new StringReader(sXML)));
    I think I am not passing the Root\\Folder correctly in generateXmlNode(“Root\\Folder”); method.
    Here is what I am passing in my code.

    Node elementOptions = generateXmlNode(“http://xxxxxxx912:9000/CPS/TitleI/er_091411_u4/Tasks”);

    Thanks
    Kapil

  60. November 23, 2012 at 01:41

    When I initially commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get several
    e-mails with the same comment. Is there any way you can remove people from
    that service? Cheers!

  61. John
    November 29, 2012 at 22:45

    Hi David,

    Your blog was very useful for us in developing custom code in java integrating with Sharepoint through it’s webservices and your examples were very useful. however we have an issue with a requirement to rename a document library. we used addList method to create the Document Library and to rename the document library, I believe we need to use updateList webservice and it has the following signature

    updateList(String listName, ListProperties listProperties, NewFields newFields, UpdateFields updateFields, DeleteFields deleteFields, String listVersion).

    now the question is how can create the classes ListProperties ,NewFields ,UpdateFields ,DeleteFields and what is the value to be passed for listVersion.

    please let us know how can we proceed to code the renaming functionality. any code would be helpful and appreciated

    Thanks,
    John

  62. au
    December 17, 2012 at 01:44

    Hi
    Great article. I followed the example and it worked first time for me.

    I am facing an issue where the getlistitem works all fine locally in my windows machine and I can get to all 83 items but when I package the app and deploy it onto a Linux server the getlistitem with the same list and view names I don’t get any items back; item count=0. I do not get any errors in fact its a 200 response also I have compared the soap request fron both machines and they both the same.

    This has been bugging me and can’t work out why it does not return any items. Has anyone come across this issue?
    Regards au

  63. Pierre-Yves
    February 7, 2013 at 09:25

    Hello,
    Thank you for your article, I encounter some problem and I would be interested to download the source code for do not ask silly question.
    Regards

  64. hindermath
    February 21, 2013 at 16:19

    Reblogged this on Hindermath's Blog und kommentierte:
    Ein sehr interessanter Artikel, der genau das Thema behandelt, mit dem ich mich gerade für unser neu entstehendes Kundenportal auseinandersetzen muss. Der Artikel kann mir bestimmt sehr nützlich sein.

  65. Ricardo
    March 20, 2013 at 16:54

    hindermath, I’m tryng to authenticate with sharepoint and consume a private list, but without success, if I send you my project, can you take a look?
    my email adress: ricardoschet@hotmail.com

  66. Jarrod
    April 16, 2013 at 17:11

    I’m attempting to recreate this but I don’t understand where in the code you define the URL to connect to, how does the application know where to send requests?

  67. jacob
    April 24, 2013 at 05:39

    How to filter the list according to a given condition?

  68. July 10, 2013 at 17:05

    PLZ give me the class MANAGER, you take SCREENSHOT FROM IT ! but you didnt post yet…

  69. February 12, 2015 at 01:48

    For anyone elses benefit too, Manager is the name of the class, wherein all the listed methods go into…

  70. June 29, 2015 at 21:42

    Is anyone able to solve the 401 exception ? I tired all the solutions provided in the comments. Putting “domain\\” in front of “username” and using Authenticator. But is still doesn’t work. I tried SAAJ too same 401 is returned. What should I do ?

    • Natalya (Nata) Tokarchuk
      March 15, 2016 at 16:24

      Run wireshark and examine your http POST packet, make sure the authentication request is correct: user name, domain is not included twice, etc. Manually try to connect to Share Point with user credentials to verify they are working. Match those in your code to have correct request in HTTP POST.

    • January 2, 2017 at 11:07

      hey haven , were you able to resolve the problem 401. Tried using authenticator still receiving the 401 error.

  71. March 4, 2016 at 12:39

    Hi David,

    Can you please tell what is the problem in my code

    Copy copy = new CopyLocator(“https://one.gbs.pre/normativa/_vti_bin/Copy.asmx?WSDL”,
    new QName(“http://schemas.microsoft.com/sharepoint/soap/”, “Copy”));

    CopySoap_PortType copySoap = copy.getCopySoap();
    BindingProvider bp = (BindingProvider) copySoap;
    bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, “SG\\GBS03512”);
    bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, “vijay123”);
    bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, “https://one.gbs.pre/normativa/_vti_bin/Copy.asmx”);

    I’m getting this error
    java.lang.ClassCastException: pre.sharept.copy.soap_axis.sharepointservice_v1.CopySoap_BindingStub
    When type casting port type with BindingProvider

    How did you instantiated the Lists interface in the code sample you provided?
    Can you please correct me?

    Thanks in Advance,
    Krish

  72. Anirudh Saligram
    March 15, 2016 at 18:39

    Hello David,

    Can you please update the source code link ? The Megaupload link is broken.

    Thanks & Regards,
    Anirudh.

  73. August 19, 2016 at 06:53

    I have a typical problem while reading the XML response from Sharepoint search result. Please see this post.

    http://stackoverflow.com/questions/39031513/read-sharepoint-search-results-using-java

    Thanks
    GP

  74. January 5, 2017 at 14:04

    Hi David,

    I have downloaded wsdl file locally.

    I am using eclipse editor and Created one Java Project for parsing wsdl file. But when I am trying to generate webservice client for it , it is not taking to the wsdl file location.

    Should I have to create web project for it or Java Project will work?

    Thanks in advance.

  75. April 5, 2017 at 11:18

    I am getting this error java.lang.Exception: Exception. See stacktrace.com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized

  76. June 16, 2017 at 06:08

    Hello,

    I am new to Java, and I am trying to do this using Java code. May I know how can I generate WSDL files here ??

  77. D W
    April 16, 2018 at 20:00

    It would be massively helpful if you showed the imports. Finding the correct imports takes more time than the guide itself.

  78. D W
    April 16, 2018 at 20:44

    The below should help complete the guide.

    Notes:
    – For ElementNSImpl you will need to import org.apache.xerces.dom.ElementNSImpl.
    – For Manager change it to whatever class you created.

    Imports you will need:
    import java.io.StringWriter;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.xml.namespace.QName;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.ws.BindingProvider;
    import org.apache.xerces.dom.ElementNSImpl;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.NodeList;
    import com.microsoft.schemas.sharepoint.soap.GetListItems;
    import com.microsoft.schemas.sharepoint.soap.GetListItemsResponse;
    import com.microsoft.schemas.sharepoint.soap.Lists;
    import com.microsoft.schemas.sharepoint.soap.ListsSoap;

  1. September 6, 2010 at 00:00
  2. December 24, 2010 at 07:38
  3. February 17, 2011 at 07:03
  4. October 11, 2012 at 00:21
  5. August 1, 2018 at 13:02

Leave a reply to Haven Liu Cancel reply