How can Upload a file to Sharepoint? - java

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

Pls follow Sharepoint guide here

Related

How to post x-www-form-urlencoded post request?

I am having troubles with posting http POST request in java. All the details are correct, but I am getting error for not valid API key.
I tried everything, and read every single post that I could find here but still no clue what is incorrect.
Here's the code:
String urlString = "https://example.com/";
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("api_key", "UTF-8")
+ "=" + URLEncoder.encode("xxxxx", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
try{
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
System.out.println(result);
} catch (IOException e){
throw(new Throwable("An error occured:\n" + e));
}

EDIT: How do I send this post Request with parameters AND form-data like this postman screenshot in JAVA?

I'm trying to send a POST request to grab comments but it doesn't work in Java while it does work with postman.
I get an 403 Forbidden error, but on postman it retrieves the data i need just fine..
Here's the Java code I'm trying to use to replicate the behavior.
String targetUrl = YOUTBE_COMMENTS_AJAX_URL;
String urlParameters = "action_load_comments=1&order_by_time=True&filter=jBjXVrS8nXs";
String updatedURL = targetUrl + "?" + urlParameters;
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(updatedURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("content-type", "multipart/form-data");
urlConnection.setRequestProperty("user-agent", "USER_AGENT");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("video_id", "UTF-8")
+ "=" + URLEncoder.encode(youtubeId, "UTF-8");
data += "&" + URLEncoder.encode("session_token", "UTF-8") + "="
+ URLEncoder.encode(xsrfToken, "UTF-8");
data += "&" + URLEncoder.encode("page_token", "UTF-8") + "="
+ URLEncoder.encode(pageToken, "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
Here's an example of what postman is sending in their headers
It seems like your problem is here (see inline comments):
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
// you wrote your URL parameters into Body
wr.flush();
wr.close();
//You closed your body and told server - you are done with request
conn.getOutputStream().write(postDataBytes);
// you wrote data into closed stream - server does not care about it anymore.
You have to append your urlParameters directly to the URL when you open it
Then you have to write your Form Data into body as you do:
conn.getOutputStream().write(postDataBytes);
and then close output stream

Problems using java HttpsURLConnection to download with authorization

I am trying to download file from a https website using java HttpsURLConnection with the Authorization header. I keep getting back the 401 response code, however, I don't have a problem using the credentials to download it through a web browser. Please help to take a look what might be wrong with my code:
File file = new File("c:/filename");
String src = "https://www.example.com/filename";
try {
file.createNewFile();
URL url = new URL(src);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
urlConnection.addRequestProperty ("Authorization", basicAuth);
urlConnection.connect();
System.out.println("code" + urlConnection.getResponseCode());
InputStream in = urlConnection.getInputStream();
OutputStream out = new FileOutputStream(file);
int d;
while ((d = in.read()) != -1) {
out.write(d);
}
in.close();
out.close();
} catch (Exception e) {
System.err.println("Failed to get the file from source. " + e);
if (file.exists()) {
file.delete();
}
}

Google Drive REST API Resumable upload returnin 400 Bad Request

I am trying to uploading chunks of 256 KB in Google Drive using REST API v3. I can successfully get the upload ID but when I use this upload ID to upload a chunk, I get a 400 Bad Request instead of 308. I am posting the code below. The method getUploadID() initiates a resumable upload session and the method putFileWithUploadID() should upload a chunk of the file but there seems to be a problem in it. I have written the code according to the official guide.
String mUploadID;
private String getUploadID(Uri fileUri, String token) {
String upload_id = "";
java.io.File fileContent = new java.io.File(fileUri.getPath());
String fileName = fileContent.getName();
String mimeType = "audio/mpeg";
try {
String url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Authorization", "Bearer " + token);
con.setRequestProperty("X-Upload-Content-Type", mimeType);
con.setRequestProperty("X-Upload-Content-Length", String.format(Locale.ENGLISH, "%d", fileContent.length()));
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
String body = "{\"name\": \"" + fileName + "\", \"parents\": [\"" + "0B7ypsm4HGZhCS3FXcldPZnFPNkE" + "\"]}";
con.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", body.getBytes().length));
OutputStream outputStream = con.getOutputStream();
outputStream.write(body.getBytes());
outputStream.close();
con.connect();
String location = con.getHeaderField("Location");
if (location.contains("upload_id")) {
String[] uploadParameters = location.split("upload_id");
upload_id = uploadParameters[1].replace("=", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return upload_id;
}
private void putFileWithUploadID(Uri fileUri, String token, long range) {
java.io.File fileContent = new java.io.File(fileUri.getPath());
String fileName = fileContent.getName();
String contentLength = String.valueOf(fileContent.length());
String mimeType = "audio/mpeg";
long totalBytesFromDataInputStream = 0;
long uploadedBytes = 0;
long chunkStart = 0;
long chunkSize = 262144;
do {
try {
String url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=" + mUploadID;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("PUT");
con.setDoOutput(true);
con.setConnectTimeout(10000);
con.setRequestProperty("Content-Type", mimeType);
uploadedBytes = chunkSize;
if (chunkStart + uploadedBytes > fileContent.length()) {
uploadedBytes = (int) fileContent.length() - chunkStart;
}
con.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", uploadedBytes));
con.setRequestProperty("Content-Range", "bytes " + chunkStart + "-" + (chunkStart + uploadedBytes - 1) + "/" + fileContent.length());
byte[] buffer = new byte[(int) uploadedBytes];
FileInputStream fileInputStream = new FileInputStream(fileContent);
fileInputStream.getChannel().position(chunkStart);
if (fileInputStream.read(buffer, 0, (int) uploadedBytes) == -1) {
break;
}
fileInputStream.close();
OutputStream outputStream = con.getOutputStream();
outputStream.write(buffer);
outputStream.close();
con.connect();
int responseCode = con.getResponseCode();
String rangeHeader = con.getHeaderField("Range");
if (rangeHeader!=null) {
chunkStart = Long.parseLong(rangeHeader.substring(rangeHeader.lastIndexOf("-") + 1, rangeHeader.length())) + 1;
}
} catch (Exception e) {
e.printStackTrace();
}
} while ((chunkStart+chunkSize)<fileContent.length());
}
Basically, 400: Bad Request means that a required field or parameter has not been provided, the value supplied is invalid, or the combination of provided fields is invalid.
This error can be thrown when trying to add a duplicate parent to a Drive item. It can also be thrown when trying to add a parent that would create a cycle in the directory graph.
You may also check this related SO post which suggested to properly use the Android-specific API to do resumable upload. See creating files.

HttpURLConnection POST, conn.getOutputStream() throwing Exception

I want to make a POST by using HttpURLConnection.
I am trying this in 2 ways, but I always get an excetion when doing: conn.getOutputStream();
The exception I get in both cases is:
java.net.SocketException: Operation timed out: connect:could be due to
invalid address
function1:
public void makePost(String title, String comment, File file) {
try {
URL servlet = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument");
HttpURLConnection conn=(HttpURLConnection)servlet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
String boundary = "---------------------------7d226f700d0";
conn.setRequestProperty("Content-type","multipart/form-data; boundary=" + boundary);
//conn.setRequestProperty("Referer", "http://127.0.0.1/index.jsp");
conn.setRequestProperty("Cache-Control", "no-cache");
OutputStream os = conn.getOutputStream(); //exception throws here!
DataOutputStream out = new DataOutputStream(os);
out.writeBytes("--" + boundary + "\r\n");
writeParam(INPUT_TITLE, title, out, boundary);
writeParam(INPUT_COMMENT, comment, out, boundary);
writeFile(INPUT_FILE, file.getName(), out, boundary);
out.flush();
out.close();
InputStream stream = conn.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
int i = 0;
while ((i = in.read()) != -1) {
System.out.write(i);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
or function 2:
public void makePost2(String title, String comment, File file) {
File binaryFile = file;
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = null;
try {
connection = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument").openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream(); //exception throws here
writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true); // true = autoFlush, important!
// Send normal param.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\""+ INPUT_TITLE +"\"");
writer.println("Content-Type: text/plain; charset=" + CHARSET);
writer.println();
writer.println(title);
// Send binary file.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\""+ INPUT_FILE +"\"; filename=\"" + binaryFile.getName() + "\"");
writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()));
writer.println("Content-Transfer-Encoding: binary");
writer.println();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
writer.println(); // Important! Indicates end of binary boundary.
// End of multipart/form-data.
writer.println("--" + boundary + "--");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) writer.close();
}
}
The URL simply cannot be reached. Either the URL is wrong, or the DNS server couldn't resolve the hostname. Try a simple connect with a well-known URL to exclude one and other, e.g.
InputStream response = new URL("http://stackoverflow.com").openStream();
// Consume response.
Update as per the comments, you're required to use a proxy server for HTTP connections. You need to configure that in the Java side as well. Add the following lines before any attempt to connect to an URL.
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
It suffices to do this only once during runtime.
See also:
Java guides - Networking and proxies
Without establishing the connection (which in this case requires 1 more step to be performed ie connect), transfer is not possible. connect() should be called after the connection is configured (ie after being done with the set***() on the connection).
What is missing is:
conn.connect();

Categories