How to set custom fields for a sharepoint document in JAVA using sharepoint rest APIs





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I need to upload a document to sharepoint and set some fields for the document using java code. I was successfully able to do the first part using below code :



Fetching the request digest:



String digestqueryURL = "<websiteURL>" +"_api/contextinfo";
URL obj = new URL(digestqueryURL);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

writing to ouput steam
con.setDoOutput(true);
con.setRequestMethod("POST");

con.setRequestProperty("User-Agent", "Java Client");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Accept", "application/json; odata=nometadata");
con.setRequestProperty("Content-Length", "2");
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("{}");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
con.connect();

int responseCode = con.getResponseCode();

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(response.toString());

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(response.toString());
String formDigest = (String)json.get("FormDigestValue");


Uploading the file:



 String uploadURL = "<websiteURL>" + "/_api/web/getfolderbyserverrelativeurl('<folderName>')/files/add(overwrite='true',url='101_16112018_1.txt')";
File file = new File("<filePath>");
if (file.length() > Integer.MAX_VALUE) {
System.out.println("File too large");
}
byte bytes = new byte[(int) file.length()];
FileInputStream ins = new FileInputStream(file);
ins.read(bytes);

URL uploadURLObj = new URL(uploadURL);
HttpsURLConnection connection=(HttpsURLConnection)uploadURLObj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("X-RequestDigest",formDigest);
connection.setRequestProperty("Content-Type", "application/json;odata=verbose");
connection.setRequestProperty("Accept", "application/json; odata=nometadata");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length",
Integer.valueOf(bytes.length).toString());
OutputStream uploadOs = connection.getOutputStream();
uploadOs.write(bytes);
uploadOs.close();
connection.connect();
Integer uploadResponseCode = connection.getResponseCode();
System.out.println(Integer.valueOf(uploadResponseCode));
BufferedReader uploadIn = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String uploadInputLine;
StringBuffer uploadResponse = new StringBuffer();
while ((uploadInputLine = uploadIn.readLine()) != null) {
uploadResponse.append(uploadInputLine);
}
System.out.println("upload res" + uploadResponse.toString());
uploadIn.close();
connection.disconnect();


I am not sure, how to get item id for the file uploaded. I could find an API that allows you to change fields for a certain itemId, so i tried fetching all the items in a folder and picked itemId for one of them and tried changing the field value for the item.



Below code doesn't work. it throws 400 error response code



Setting fields for itemId:



  String fieldInfo = "{ "__metadata": { "type":
"SP.Data.ControlroomdatabaseItem" }, "Title": "TestUpdated"}";
byte b = fieldInfo.getBytes();
String uploadURL2 = "https://sharepoint.deshaw.com/compliance/_api/web/lists/GetByTitle('<folderName>')/items(<itemId>)";
URL uploadURLObj2 = new URL(uploadURL2);
HttpsURLConnection connection2 = (HttpsURLConnection) uploadURLObj2.openConnection();
connection2.setRequestMethod("POST");
connection2.setRequestProperty("X-RequestDigest",formDigest);

connection2.setRequestProperty("Accept", "application/json; odata=verbose");

connection2.setDoOutput(true);
connection2.setRequestProperty("Content-Length", Integer.valueOf(b.length).toString());
OutputStream uploadOs2 = connection2.getOutputStream();
uploadOs2.write(b);
uploadOs2.close();

connection2.connect();

Integer uploadResponseCode2 = connection2.getResponseCode();


System.out.println(Integer.valueOf(uploadResponseCode2));

BufferedReader uploadIn2 = new BufferedReader(
new InputStreamReader(connection2.getInputStream()));
String uploadInputLine2;
StringBuffer uploadResponse2 = new StringBuffer();

while ((uploadInputLine2 = uploadIn2.readLine()) != null) {
uploadResponse2.append(uploadInputLine2);
}
System.out.println(uploadResponse2.toString());
uploadIn2.close();
connection2.disconnect();


What is the correct way to set fields for file uploaded?










share|improve this question































    0















    I need to upload a document to sharepoint and set some fields for the document using java code. I was successfully able to do the first part using below code :



    Fetching the request digest:



    String digestqueryURL = "<websiteURL>" +"_api/contextinfo";
    URL obj = new URL(digestqueryURL);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    writing to ouput steam
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    con.setRequestProperty("User-Agent", "Java Client");
    con.setRequestProperty("Content-Type", "application/json;odata=verbose");
    con.setRequestProperty("Accept", "application/json; odata=nometadata");
    con.setRequestProperty("Content-Length", "2");
    OutputStream os = con.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
    osw.write("{}");
    osw.flush();
    osw.close();
    os.close(); //don't forget to close the OutputStream
    con.connect();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    }
    in.close();
    con.disconnect();
    System.out.println(response.toString());

    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(response.toString());
    String formDigest = (String)json.get("FormDigestValue");


    Uploading the file:



     String uploadURL = "<websiteURL>" + "/_api/web/getfolderbyserverrelativeurl('<folderName>')/files/add(overwrite='true',url='101_16112018_1.txt')";
    File file = new File("<filePath>");
    if (file.length() > Integer.MAX_VALUE) {
    System.out.println("File too large");
    }
    byte bytes = new byte[(int) file.length()];
    FileInputStream ins = new FileInputStream(file);
    ins.read(bytes);

    URL uploadURLObj = new URL(uploadURL);
    HttpsURLConnection connection=(HttpsURLConnection)uploadURLObj.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("X-RequestDigest",formDigest);
    connection.setRequestProperty("Content-Type", "application/json;odata=verbose");
    connection.setRequestProperty("Accept", "application/json; odata=nometadata");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Length",
    Integer.valueOf(bytes.length).toString());
    OutputStream uploadOs = connection.getOutputStream();
    uploadOs.write(bytes);
    uploadOs.close();
    connection.connect();
    Integer uploadResponseCode = connection.getResponseCode();
    System.out.println(Integer.valueOf(uploadResponseCode));
    BufferedReader uploadIn = new BufferedReader(
    new InputStreamReader(connection.getInputStream()));
    String uploadInputLine;
    StringBuffer uploadResponse = new StringBuffer();
    while ((uploadInputLine = uploadIn.readLine()) != null) {
    uploadResponse.append(uploadInputLine);
    }
    System.out.println("upload res" + uploadResponse.toString());
    uploadIn.close();
    connection.disconnect();


    I am not sure, how to get item id for the file uploaded. I could find an API that allows you to change fields for a certain itemId, so i tried fetching all the items in a folder and picked itemId for one of them and tried changing the field value for the item.



    Below code doesn't work. it throws 400 error response code



    Setting fields for itemId:



      String fieldInfo = "{ "__metadata": { "type":
    "SP.Data.ControlroomdatabaseItem" }, "Title": "TestUpdated"}";
    byte b = fieldInfo.getBytes();
    String uploadURL2 = "https://sharepoint.deshaw.com/compliance/_api/web/lists/GetByTitle('<folderName>')/items(<itemId>)";
    URL uploadURLObj2 = new URL(uploadURL2);
    HttpsURLConnection connection2 = (HttpsURLConnection) uploadURLObj2.openConnection();
    connection2.setRequestMethod("POST");
    connection2.setRequestProperty("X-RequestDigest",formDigest);

    connection2.setRequestProperty("Accept", "application/json; odata=verbose");

    connection2.setDoOutput(true);
    connection2.setRequestProperty("Content-Length", Integer.valueOf(b.length).toString());
    OutputStream uploadOs2 = connection2.getOutputStream();
    uploadOs2.write(b);
    uploadOs2.close();

    connection2.connect();

    Integer uploadResponseCode2 = connection2.getResponseCode();


    System.out.println(Integer.valueOf(uploadResponseCode2));

    BufferedReader uploadIn2 = new BufferedReader(
    new InputStreamReader(connection2.getInputStream()));
    String uploadInputLine2;
    StringBuffer uploadResponse2 = new StringBuffer();

    while ((uploadInputLine2 = uploadIn2.readLine()) != null) {
    uploadResponse2.append(uploadInputLine2);
    }
    System.out.println(uploadResponse2.toString());
    uploadIn2.close();
    connection2.disconnect();


    What is the correct way to set fields for file uploaded?










    share|improve this question



























      0












      0








      0








      I need to upload a document to sharepoint and set some fields for the document using java code. I was successfully able to do the first part using below code :



      Fetching the request digest:



      String digestqueryURL = "<websiteURL>" +"_api/contextinfo";
      URL obj = new URL(digestqueryURL);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

      writing to ouput steam
      con.setDoOutput(true);
      con.setRequestMethod("POST");

      con.setRequestProperty("User-Agent", "Java Client");
      con.setRequestProperty("Content-Type", "application/json;odata=verbose");
      con.setRequestProperty("Accept", "application/json; odata=nometadata");
      con.setRequestProperty("Content-Length", "2");
      OutputStream os = con.getOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
      osw.write("{}");
      osw.flush();
      osw.close();
      os.close(); //don't forget to close the OutputStream
      con.connect();

      int responseCode = con.getResponseCode();

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
      }
      in.close();
      con.disconnect();
      System.out.println(response.toString());

      JSONParser parser = new JSONParser();
      JSONObject json = (JSONObject) parser.parse(response.toString());
      String formDigest = (String)json.get("FormDigestValue");


      Uploading the file:



       String uploadURL = "<websiteURL>" + "/_api/web/getfolderbyserverrelativeurl('<folderName>')/files/add(overwrite='true',url='101_16112018_1.txt')";
      File file = new File("<filePath>");
      if (file.length() > Integer.MAX_VALUE) {
      System.out.println("File too large");
      }
      byte bytes = new byte[(int) file.length()];
      FileInputStream ins = new FileInputStream(file);
      ins.read(bytes);

      URL uploadURLObj = new URL(uploadURL);
      HttpsURLConnection connection=(HttpsURLConnection)uploadURLObj.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("X-RequestDigest",formDigest);
      connection.setRequestProperty("Content-Type", "application/json;odata=verbose");
      connection.setRequestProperty("Accept", "application/json; odata=nometadata");
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-Length",
      Integer.valueOf(bytes.length).toString());
      OutputStream uploadOs = connection.getOutputStream();
      uploadOs.write(bytes);
      uploadOs.close();
      connection.connect();
      Integer uploadResponseCode = connection.getResponseCode();
      System.out.println(Integer.valueOf(uploadResponseCode));
      BufferedReader uploadIn = new BufferedReader(
      new InputStreamReader(connection.getInputStream()));
      String uploadInputLine;
      StringBuffer uploadResponse = new StringBuffer();
      while ((uploadInputLine = uploadIn.readLine()) != null) {
      uploadResponse.append(uploadInputLine);
      }
      System.out.println("upload res" + uploadResponse.toString());
      uploadIn.close();
      connection.disconnect();


      I am not sure, how to get item id for the file uploaded. I could find an API that allows you to change fields for a certain itemId, so i tried fetching all the items in a folder and picked itemId for one of them and tried changing the field value for the item.



      Below code doesn't work. it throws 400 error response code



      Setting fields for itemId:



        String fieldInfo = "{ "__metadata": { "type":
      "SP.Data.ControlroomdatabaseItem" }, "Title": "TestUpdated"}";
      byte b = fieldInfo.getBytes();
      String uploadURL2 = "https://sharepoint.deshaw.com/compliance/_api/web/lists/GetByTitle('<folderName>')/items(<itemId>)";
      URL uploadURLObj2 = new URL(uploadURL2);
      HttpsURLConnection connection2 = (HttpsURLConnection) uploadURLObj2.openConnection();
      connection2.setRequestMethod("POST");
      connection2.setRequestProperty("X-RequestDigest",formDigest);

      connection2.setRequestProperty("Accept", "application/json; odata=verbose");

      connection2.setDoOutput(true);
      connection2.setRequestProperty("Content-Length", Integer.valueOf(b.length).toString());
      OutputStream uploadOs2 = connection2.getOutputStream();
      uploadOs2.write(b);
      uploadOs2.close();

      connection2.connect();

      Integer uploadResponseCode2 = connection2.getResponseCode();


      System.out.println(Integer.valueOf(uploadResponseCode2));

      BufferedReader uploadIn2 = new BufferedReader(
      new InputStreamReader(connection2.getInputStream()));
      String uploadInputLine2;
      StringBuffer uploadResponse2 = new StringBuffer();

      while ((uploadInputLine2 = uploadIn2.readLine()) != null) {
      uploadResponse2.append(uploadInputLine2);
      }
      System.out.println(uploadResponse2.toString());
      uploadIn2.close();
      connection2.disconnect();


      What is the correct way to set fields for file uploaded?










      share|improve this question
















      I need to upload a document to sharepoint and set some fields for the document using java code. I was successfully able to do the first part using below code :



      Fetching the request digest:



      String digestqueryURL = "<websiteURL>" +"_api/contextinfo";
      URL obj = new URL(digestqueryURL);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

      writing to ouput steam
      con.setDoOutput(true);
      con.setRequestMethod("POST");

      con.setRequestProperty("User-Agent", "Java Client");
      con.setRequestProperty("Content-Type", "application/json;odata=verbose");
      con.setRequestProperty("Accept", "application/json; odata=nometadata");
      con.setRequestProperty("Content-Length", "2");
      OutputStream os = con.getOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
      osw.write("{}");
      osw.flush();
      osw.close();
      os.close(); //don't forget to close the OutputStream
      con.connect();

      int responseCode = con.getResponseCode();

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
      }
      in.close();
      con.disconnect();
      System.out.println(response.toString());

      JSONParser parser = new JSONParser();
      JSONObject json = (JSONObject) parser.parse(response.toString());
      String formDigest = (String)json.get("FormDigestValue");


      Uploading the file:



       String uploadURL = "<websiteURL>" + "/_api/web/getfolderbyserverrelativeurl('<folderName>')/files/add(overwrite='true',url='101_16112018_1.txt')";
      File file = new File("<filePath>");
      if (file.length() > Integer.MAX_VALUE) {
      System.out.println("File too large");
      }
      byte bytes = new byte[(int) file.length()];
      FileInputStream ins = new FileInputStream(file);
      ins.read(bytes);

      URL uploadURLObj = new URL(uploadURL);
      HttpsURLConnection connection=(HttpsURLConnection)uploadURLObj.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("X-RequestDigest",formDigest);
      connection.setRequestProperty("Content-Type", "application/json;odata=verbose");
      connection.setRequestProperty("Accept", "application/json; odata=nometadata");
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-Length",
      Integer.valueOf(bytes.length).toString());
      OutputStream uploadOs = connection.getOutputStream();
      uploadOs.write(bytes);
      uploadOs.close();
      connection.connect();
      Integer uploadResponseCode = connection.getResponseCode();
      System.out.println(Integer.valueOf(uploadResponseCode));
      BufferedReader uploadIn = new BufferedReader(
      new InputStreamReader(connection.getInputStream()));
      String uploadInputLine;
      StringBuffer uploadResponse = new StringBuffer();
      while ((uploadInputLine = uploadIn.readLine()) != null) {
      uploadResponse.append(uploadInputLine);
      }
      System.out.println("upload res" + uploadResponse.toString());
      uploadIn.close();
      connection.disconnect();


      I am not sure, how to get item id for the file uploaded. I could find an API that allows you to change fields for a certain itemId, so i tried fetching all the items in a folder and picked itemId for one of them and tried changing the field value for the item.



      Below code doesn't work. it throws 400 error response code



      Setting fields for itemId:



        String fieldInfo = "{ "__metadata": { "type":
      "SP.Data.ControlroomdatabaseItem" }, "Title": "TestUpdated"}";
      byte b = fieldInfo.getBytes();
      String uploadURL2 = "https://sharepoint.deshaw.com/compliance/_api/web/lists/GetByTitle('<folderName>')/items(<itemId>)";
      URL uploadURLObj2 = new URL(uploadURL2);
      HttpsURLConnection connection2 = (HttpsURLConnection) uploadURLObj2.openConnection();
      connection2.setRequestMethod("POST");
      connection2.setRequestProperty("X-RequestDigest",formDigest);

      connection2.setRequestProperty("Accept", "application/json; odata=verbose");

      connection2.setDoOutput(true);
      connection2.setRequestProperty("Content-Length", Integer.valueOf(b.length).toString());
      OutputStream uploadOs2 = connection2.getOutputStream();
      uploadOs2.write(b);
      uploadOs2.close();

      connection2.connect();

      Integer uploadResponseCode2 = connection2.getResponseCode();


      System.out.println(Integer.valueOf(uploadResponseCode2));

      BufferedReader uploadIn2 = new BufferedReader(
      new InputStreamReader(connection2.getInputStream()));
      String uploadInputLine2;
      StringBuffer uploadResponse2 = new StringBuffer();

      while ((uploadInputLine2 = uploadIn2.readLine()) != null) {
      uploadResponse2.append(uploadInputLine2);
      }
      System.out.println(uploadResponse2.toString());
      uploadIn2.close();
      connection2.disconnect();


      What is the correct way to set fields for file uploaded?







      java rest sharepoint-2013






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 17:31









      Eamon Scullion

      683313




      683313










      asked Nov 16 '18 at 16:56









      Priyanka SharmaPriyanka Sharma

      11




      11
























          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342276%2fhow-to-set-custom-fields-for-a-sharepoint-document-in-java-using-sharepoint-rest%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342276%2fhow-to-set-custom-fields-for-a-sharepoint-document-in-java-using-sharepoint-rest%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Error while running script in elastic search , gateway timeout

          Adding quotations to stringified JSON object values