I'm attempting to use the gdata project from an android app. I'm attempting to upload a new csv file to google docs, but I keep encountering a 411 error (Content-Length).
My code looks something like:
GoogleService ss = new SpreadsheetService("testApp");
ss.setUserCredentials("<username>", "<password>");
DocumentListEntry newEntry = null;
newEntry = new DocumentListEntry();
newEntry.setTitle(new PlainTextConstruct("my.csv"));
TextConstruct tc = TextConstruct.plainText("1,2,3,4,5,6,7,8,9,10");
newEntry.setContent(new TextContent(tc));
DocumentListEntry res = ss.insert(new URL("https://docs.google.com/feeds/default/private/full/"), newEntry);
Since the GData lib is abstracting the network calls from me I assume that I don't need to set the Content-Length myself, which leads to me believe I'm simply not using the lib correctly.
What am I missing? Thanks.
The content of the file should not be set in the metadata but sent along the metadata using an HTTP multipart request.
The client library takes care of doing that and you can set the content using:
newEntry.setFile(/* java.io.File instance */ file, /* MIME type */ "text/csv");
This requires to load the data from a file, but you can use streams to load from memory.
A more detailed example can be found in the Java client library project page.
Related
I want to copy a single json file from Unity's Assets/Resources/ directory to the internal persistent memory of Android device (INTERNAL STORAGE/Android/data/<packagename>/files/) only once at the start of the game. I looked up all over the internet, with solutions saying to use Streaming assets and UnityWebRequests or WWW class which is obsolete now. I tried everything for hours now. And did not find a exact solutions, but only got null references and directory not found.
I added my json file to the <UnityProject>/Assets/Resources/StreamingAssets/, but it doesn't seem to detect any streaming assets. I understand an apk is a zip file and so I can only read the contents of streaming assets, but my I can't find a solution to this.
Once I get my json from streaming asset, I can finally add it to Application.persistentDataPath.
UPDATE
I had actually figured it out,
public void LoadFromResources() {
{mobilePath = "StreamingAssets/"; mobilePath = mobilePath + "stickerJson" + ".json";
string newPath = mobilePath.Replace(".json", "");
TextAsset ta = Resources.Load<TextAsset>(newPath);
string json = ta.text; Debug.Log(json); System.IO.File.WriteAllText(Application.persistentDataPath + "/stickers.json", json);
}
}
To copy a file you only need to have the information of the file and then create a new one in another place.
So if you got your json file into your Resources directory you can retreive like the documentation say:
//Load text from a JSON file (Assets/Resources/Text/jsonFile01.json)
var jsonTextFile = Resources.Load<TextAsset>("Text/jsonFile01");
//Then use JsonUtility.FromJson<T>() to deserialize jsonTextFile into an object
Then you only have to create your android file in your persistentDataPath as #Iggy says in the comments doing:
System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "file.txt"), jsonTextFile);
Note: Not really sure, but for other cases I think that StreamingAssets folder should be inside Assets, no inside Resources.
I have some encrypted (AES-128) .m3u8 stream in my Android app and I want to play it in ExoPlayer. I have for this two variables:
val secretKey = "a4cd9995a1aa91e1"
val initVector = "0000000000000000"
As I read in docs I need to add URI and IV parameters into source file. After adding I have the next one:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:6
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-DISCONTINUITY
#EXT-X-KEY:METHOD=AES-128,URI="data:text/plain;charset=utf-8,a4cd9995a1aa91e1",IV=0x30303030303030303030303030303030
#EXTINF:6.0,
media_b525000_0.ts
#EXTINF:6.0,
media_b525000_1.ts
#EXTINF:6.0,
media_b525000_2.ts
*other .ts segments...*
where I added two lines: #EXT-X-DISCONTINUITY and #EXT-X-KEY. But the player doesnt play the stream and I have the next exception:
com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Malformed URL
What did I do wrong? And how can I to decrypt stream when I have secretKey and initVector?
Exoplayer assumes anything following URI is an actual URL in m3u8 file and when it tries to load the encryption key using the below url which is invalid, above exception is thrown by OkHttpDataSource class.
URI="data:text/plain;charset=utf-8,a4cd9995a1aa91e1"
This problem can be solved in two ways.
1. Place the encryption key in a server and use a URL to fetch it.
2. Implement custom data source classes and implement, intercept the calls and modify the request/response objects as per your need.
I have faced similar issue but in my case i have a custom scheme instead of http. Default OkHttpDataSource does not handle custom url schemes hence i had to write my own data source and intercept.
Dropbox now have an apsolutely new API, which is absolutely differ from the old one (it's interesting why), but there's no ANY actual examples in the internet, so I've found only some code in their examples. Here is it:
// Download the file.
try (OutputStream outputStream = new FileOutputStream (file)) {
mDbxClient.files ()
.download (metadata.getPathLower (), metadata.getRev ())
.download (outputStream);
}
I need to download file from remote folder to the local one, so I need to use this path for example:
.download ("Backups/backup.ab", "/storage/sdcard/Folder/backup.ab")
I've tried it, but get a error
IllegalArgumentException: String 'rev' does not match pattern'
Do you know, what it can be, and metadata.getPathLower () and metadata.getRev () methods are using for? I've learned, that metadata var gets from the first argv from execute (), but what this functions do?
Thanks a lot!
Not sure if if works for android. I have posted the following method just in case someone is looking for a C# .net solution.
private async Task Download(DropboxClient dbx, string folder, string file, string localFilePath)
{
using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
{
using (var fileStream = File.Create(localFilePath))
{
(await response.GetContentAsStreamAsync()).CopyTo(fileStream);
}
}
}
Parameter example:
file = "YourFileName.pdf";
folder = "/YourDropboxFolderName";
localFilePath = #"C:\Users\YourUserName\YourFileName.pdf";
The Dropbox API v2 Java SDK's download method takes these two parameters:
String path
String rev
Per the download method documentation there, the first is the remote path of the file in Dropbox you want to download, and the second is the identifier for the revision of the file you want. The second parameter is not the local path where you want to save the file, as it appears you're supplying in your code. Instead, you save the file content using the .download (outputStream); portion of the sample code you posted, e.g., as also shown in this sample code.
Also, as stated in the documentation, the second parameter is deprecated and should no longer be used. You can just use the version of the download method that only takes the one parameter. The code for using it is otherwise the same as the sample.
For reference, in the sample, the metadata object is an instance of FileMetadata. You can find more information on the getPathLower and getRev methods in the documentation as well.
I am Creating a small Apps from that user can upload his MS office file to his registered mail ID G_Drive account from android device.
and export that file into PDF Format.
for that i taken help form below link :
https://developers.google.com/drive/v2/reference/files/insert#examples
https://developers.google.com/drive/manage-downloads#downloading_google_documents
i created application, and its working fine for small size(< 1MB) file, but when i am sending large size to the g_Drive than i am getting below errors:
java.io.exception Unexpected End of Stream
java.net.SocketTimeoutException: Read timed out
i tried for Resumable upload, but the insert method doesn't have parameter to set this.
if am setting the upload type to resumable with
service.files().insert(body, mediaContent).set("upload type", "resumable");
or
Insert insertService = service.files().insert(body, mediaContent).setConvert(true);
insertService.getMediaHttpUploader().setDirectUploadEnabled(false); insertService.getMediaHttpUploader().setChunkSize(MediaHttpUploader.DEFAULT_CHUNK_SIZE);
file = insertService.execute();
than also its generating same errors.
same case with downloading also.....
please send me some solutions...for this...
Don't use basic upload for files larger than 5MB.
You need to set the content length of the media content before starting to upload. Otherwise, it's likely that Google endpoint can't recognize the upload's being finished and it waits until the socket is being timed out.
InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(
new FileInputStream(UPLOAD_FILE)));
mediaContent.setLength(UPLOAD_FILE.length());
Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setProgressListener(new FileUploadProgressListener());
insert.execute();
There is actually a complete Android based resumable upload sample on [1].
To edit a Google Drive native doc on my Android app, I'm downloading the file to a .docx format (converting), editing the file in an editor capable of editing MS Word docx files, then I'm uploading the file back to its native Google doc format.
I'm using the following code:
File liveFileInfo = sService.files().get(mItem.getFileId()).execute();
mInputStream = new FileInputStream(pFile); //pFile is the java.io.File of the source XXX.docx file
InputStreamContent mediaContent = new InputStreamContent("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
new BufferedInputStream(mInputStream));
mediaContent.setLength(pFile.length());
Drive.Files.Update update = sService.files().update(mItem.getFileId(), liveFileInfo, mediaContent);
update.setConvert(true);
MediaHttpUploader uploader = update.getMediaHttpUploader();
int chunkSize = getChunkSize(mItem);
uploader.setChunkSize(chunkSize);
uploader.setProgressListener(new MediaHttpUploaderProgressListener() {
#Override
public void progressChanged(MediaHttpUploader uploader)
throws IOException {
// update UI
}
});
File uploadedFile = update.execute();
The code runs without errors, but the contents of the file contains all the weird characters you normally see when the wrong format is uploaded or an incorrect file type.
So my question is whether it is possible to update an existing file using this process? Or is the conversion process only supported with INSERTed files? Is there anything wrong with the code above?
I figured out what I missed. Add the following line to the code above to fix the problem:
liveFileInfo.setMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");