Java
Chilkat2 Java
Google Drive Multipart Upload String
See more REST Examples
Demonstrates a file upload to Google Drive where the contents of the file are contained in a string variable.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.AuthGoogle;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
// This example will upload a file to Google Drive.
success = true;
// It requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
AuthGoogle gAuth = new AuthGoogle();
gAuth.setScope("https://www.googleapis.com/auth/drive");
gAuth.setSubEmailAddress("some.user@example.com");
gAuth.setExpireNumSeconds(3600);
// Obtain an access token as shown in one of the following examples:
// See Get Access Token using a Service Account JSON Key
// See Get Access Token using a P12 File
Rest rest = new Rest();
// Connect using TLS.
boolean bAutoReconnect = true;
rest.connect("www.googleapis.com", 443, true, bAutoReconnect);
// Provide the authentication credentials (i.e. the access key)
rest.setAuthGoogle(gAuth);
// A multipart upload to Google Drive needs a multipart/related Content-Type
rest.addHeader("Content-Type", "multipart/related");
// Specify each part of the request.
// The 1st part is JSON with information about the file.
rest.setPartSelector("1");
rest.addHeader("Content-Type", "application/json; charset=UTF-8");
JsonObject json = new JsonObject();
json.addStringAt(-1, "title", "helloWorld.txt");
json.addStringAt(-1, "description", "A simple text file that says Hello World.");
json.addStringAt(-1, "mimeType", "text/plain");
rest.setMultipartBodyString(json.emit());
// The 2nd part is the file content.
// In this case, we'll upload a simple text file containing "Hello World!"
rest.setPartSelector("2");
rest.addHeader("Content-Type", "text/plain");
rest.setMultipartBodyString("Hello World!");
// POST https://www.googleapis.com/upload/drive/v2/files
String jsonResponse;
try {
jsonResponse = rest.fullRequestMultipart("POST", "/upload/drive/v2/files?uploadType=multipart");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Show the JSON response.
System.out.println("Response Status Code: " + rest.getResponseStatusCode());
System.out.println("Json Response: " + jsonResponse);
}
}