Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

how to check sharepoint's modern page url if file exists in java

  1. User

    how to check sharepoint's modern page url if file exists in java

  2. Assistant

    You can use the SharePoint REST API to check if a file exists on a modern SharePoint page. Here's a sample Java code to achieve this:

    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class SharePointPageChecker {
        
        public static void main(String[] args) {
            String siteUrl = "https://your-sharepoint-site-url";
            String filePath = "/sites/your-site/Shared%20Documents/file.txt";
    
            try {
                // Construct the REST API URL
                String apiUrl = siteUrl + "/_api/web/GetFileByServerRelativeUrl('" + filePath + "')";
    
                URL url = new URL(apiUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Accept", "application/json");
    
                // Check if the file exists
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("File exists.");
                } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                    System.out.println("File does not exist.");
                } else {
                    System.out.println("Error occurred: " + responseCode);
                }
    
                connection.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    

    Make sure to replace your-sharepoint-site-url with the URL of your SharePoint site and your-site and file.txt with the appropriate values in the filePath variable.

    This code sends a GET request to the SharePoint REST API endpoint for the file and checks the response code. If the file exists, it will return 200 (HTTP_OK), otherwise it will return 404 (HTTP_NOT_FOUND).