KangDo
KangDo

Reputation: 79

How can Upload a file to Sharepoint?

private void uploadDocToSharePoint(String token, Resource resource, String folderName) {
    try {
        String uploadUrl = Utils.SHARE_POINT_DOMAIN + "_api/web/getfolderbyserverrelativeurl('" + folderName + "')/files/add(url='" + resource.getFilename() + "', overwrite=true)";
        URL url = new URL(uploadUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

        // Set Header
        httpConn.setDoOutput(true);
        httpConn.setDoOutput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Authorization", "Bearer " + token);
        httpConn.setRequestProperty("accept", "application/json; odata=verbose");
        httpConn.setRequestProperty("Content-Type", "application/xml");

        OutputStream os = httpConn.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
        osw.write("Just Some Text");
        osw.flush();
        osw.close();
        os.close();  //don't forget to close the OutputStream
        httpConn.connect();


        System.out.println(httpConn.getResponseCode());
        System.out.println(httpConn.getResponseMessage());
        String result;
        BufferedInputStream bis = new BufferedInputStream(httpConn.getInputStream());
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int result2 = bis.read();
        while(result2 != -1) {
            buf.write((byte) result2);
            result2 = bis.read();
        }
        result = buf.toString();
        System.out.println(result);


    } catch (Exception e) {
        System.out.println("Error while reading file: " + e.getMessage());
    }
}

httpConn.getResponseCode() is 400 and httpConn.getResponseMessage() is Bad Request.

I have tested this request with the URL generated in this class on Postman. it works correctly. so I am sure about url and token is correct. It creates an Empty file successfully. But as I mentioned the response status is 400 and Bad Request.

I am not sure what is wrong with the following class

Sharepoint guide here

My class copied from here

screenshot here

Upvotes: 1

Views: 395

Answers (1)

Javier Gallego
Javier Gallego

Reputation: 184

Pls follow Sharepoint guide here

Upvotes: 1

Related Questions