Uploading files to Onedrive using REST API - rest

I am trying to upload a file into OneDrive using its REST API. This is what I am trying to accomplish based on documentation available at OneDrive Rest API:
POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN
Content-Type: multipart/form-data; boundary=A300x
--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream
Hello, World!
--A300x--
This is what I have:
Uri destination = new Uri(string.Format("https://apis.live.net/v5.0/{0}/files?", folder.ID));
BackgroundUploader uploader = new BackgroundUploader ();
uploader.SetRequestHeader("Authorization", "Bearer " + account.AccessToken);
uploader.SetRequestHeader("Content-Type", "multipart/form-data; boundary=\"foo_bar_baz\"");
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
BackgroundTransferContentPart metaDataPart = new BackgroundTransferContentPart();
metaDataPart.SetHeader("Content-Disposition", "form-data; name=\"file\";filename=\""+content.Name+"\"");
parts.Add(metaDataPart);
BackgroundTransferContentPart contentPart = new BackgroundTransferContentPart();
contentPart.SetHeader("Content-Type", content.ContentType);
// content is a StorageFile
contentPart.SetFile(content);
response.UploadOperation = await uploader.CreateUploadAsync(destination, parts, "form-data", "foo_bar_baz");
This line below causes an Access violation error and the Windows Store app crashes:
response.UploadOperation = await uploader.CreateUploadAsync(destination, parts, "form-data", "foo_bar_baz");

You are creating two BackgroundTransferContentPart and only adding the fist to your 'List'.
I think you only need one, something like this:
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
BackgroundTransferContentPart metaDataPart = new BackgroundTransferContentPart();
metaDataPart.SetHeader("Content-Disposition",
"form-data; name=\"file\";filename=\"" + content.Name + "\"");
metaDataPart.SetHeader("Content-Type", content.ContentType);
metaDataPart.SetFile(content);
parts.Add(metaDataPart);
UPDATE: Ok, the above code fixed the Access Violation issue. Why you are getting a 400 error is a mystery.
But another way to upload a file to OneDrive is using the PUT method:
Uri putUri = new Uri(string.Format("https://apis.live.net/v5.0/{0}/files/{1}",
"folder.a4fb14adbccd1917.A4FB14ADBCCD1917!32089",
content.Name));
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Authorization", "Bearer " + accessToken);
uploader.Method = "PUT";
UploadOperation putOperation = uploader.CreateUpload(putUri, content);
await putOperation.StartAsync();
Have you tried PUT?

Related

How to Yahoo ads conversion tracker name through yahoo api

I want to change Yahoo ads conversion tracker name through API automatically.
But, when I run the following code, that returned an error.
access_token = XXXXXXXXXXXXX
account_id = XXXXXX
conversion_id = XXXXXXX
new_name = "new_name"
header = {"Content-Type": "application/json",\
"Accept": "application/json",\
"Authorization": "Bearer " + access_token}
url = "https://ads-search.yahooapis.jp/api/v8/ConversionTrackerService/set"
data = {'accountId':account_id, 'operand':[{'accountId': account_id, 'conversionTrackerId': conversion_id, "conversionTrackerName": new_name}]}
data = json.dumps(data).encode()
req = urllib.request.Request(url, data=data, method='POST', headers=header)
try:
with urllib.request.urlopen(req) as response:
body = json.loads(response.read())
headers = response.getheaders()
status = response.getcode()
print(headers)
print(status)
print(body)
except urllib.error.URLError as e:
print(e.reason)`
Retuened error is:
{'errors': [{'code': 'L0001', 'message': 'Lower list size.', 'details': [{'requestKey': 'operand', 'requestValue': None}]}], 'rid': '6fab0e1ac60dd2a871831484791976bf', 'rval': None}
I guess the length of "operand" field is 1 and it is right length according to yahoo api document. What I shuold do to fix this error?
I tryied to make length of "operand" field 2. But the result was same.

SoapUI POST to REST with attached file in Groovy

I'm trying to POST to a Sharepoint REST service an attached file with SoapUI Pro. I've tried the examples at: https://support.smartbear.com/readyapi/docs/requests/attachment/rest.html
But with no luck.
It should work with POST with byte-array as body. But how do I do that in SoapUI and Groovy?
In the tool Insomnia it works with "Binary File".
I add these headers:
Accept: application/json;odata=verbose
Content-Type: application/octet-stream
Media type = multipart/mixed and Post QueryString
But the file won't be uploaded to SharePoint.
PowerShell code that works:
$headers = #{
'X-RequestDigest' = 'xxxxxxxxxxxxxxxxxxxxxxx'
'Accept' = 'application/json;odata=verbose'
}
$document = [System.IO.File]::ReadAllBytes('C:\temp\myFile.docx')
Invoke-RestMethod -Method Post -UseDefaultCredentials -Uri "https://xxxx.xxx/add(url='myFile.docx',%20overwrite=true)" -Headers $headers -Body $document
I tried to go through this as well a while ago but I found it easier to use HTTP to do this.
You may try to see if it fits your requirements
My groovy script for attachment :
// upload source file before import
// get uploading request
def source_file = context.expand( '${#TestCase#source_file_path}' )
log.info "upload $source_file"
def aPIToolsTestSuite = context.expand( '${#Project#APIToolsTestSuite}' ) // the test suite that contains the test case with the HTTP request
tc_name = "import - upload resource files"
request = testRunner.testCase.testSuite.project.testSuites[aPIToolsTestSuite].testCases[tc_name].getTestStepByName("Request 1").testRequest
// clear request from any existing attachment
for (a in request.attachments)
{
request.removeAttachment(a)
}
// attach file to upload
def file = new File(source_file)
if (file == null)
{
log.error "bad file name : $source_file"
}
else
{
// attach file and set properties
try{
def attachment = request.attachFile (file, true)
attachment.contentType = "application/octet-stream"
attachment.setPart("upload file '$source_file'")
}
catch (Exception e){
log.error "file ${file.name} : exception $e"
}
}
// now upload file - launch the request
def jsonSlurper = new groovy.json.JsonSlurper()
def TC;
def async = false
TC = testRunner.testCase.testSuite.project.getTestSuiteByName(aPIToolsTestSuite).getTestCaseByName(tc_name)
result = TC.run (context.getProperties(), async)
if (String.valueOf( result.status ) != "PASS")
{
msg = "unexpected failure during $tc_name when uploading $source_file"
testRunner.fail(msg)
log.error msg
}
else
{
// this part is for further processing
// file uploaded, go through the import and properties backup process
resource_to_import = TC.getPropertyValue("testResponse").split('\"')[1]
// file uploaded, go through the import and properties backup process
testRunner.testCase.setPropertyValue("resource_id", resource_to_import)
}
And the HTTP request contained in the test case APIToolsTestSuite/import - upload resource files
first step : get endpoint
def env = testRunner.testCase.testSuite.project.activeEnvironment
rest = env.getRestServiceAt(0)
config = rest.getEndpoint().config
endpoint = new XmlSlurper().parseText(config.toString())
testRunner.testCase.setPropertyValue("endpoint", endpoint.toString())
second step, HTTP request:
POST
with Request tab parameters :
name : metadata
value : {"storageType":"FILESYSTEM","itemName":"my_source_file"}
type : QUERY
media type : multipart/form-data
Post QueryString
Headers : application/json
Good luck :)

Curl Post request to upload .zip file to Sharepoint returning "Compressed (zipped) folder invalid when downloading

I have a curl Post request that attempts to upload the latest documents to our Sharepoint. It appears to work fine, the file I send is valid and opens fine before I send it. Once it arrives on sharepoint the filesize is the same but when I download it appears to be corrupted and wont open.
I have tried manually uploading the zip file to Sharepoint, it works fine this way.
I have also scanned the internet for some solution to the problem but I am unable to find anything.
curl -X POST
"http://12.3.456.78:8080/TEST-2.0/sharepoint?relativePath=Shared%20Documents%2FRelease%20Documents%2Fv1&teamSite=Test"
-H "accept: /" -H "Content-Type: multipart/form-data" -F "file=#Test.zip;type=application/x-zip-compressed"
I expect the file on sharepoint to be valid and open correctly after download but I get the following error.
"Windows cannot open the folder.
The Compressed (zipped) Folder 'C:\Test.zip' is invalid.'
The answer was within the code, although the file was sending, it was obviously not sending correctly which was causing the corruption.
The line that I added that made the difference was the following.
post.setEntity( new FileEntity(file) );
My full method can be found below, feel free to comment if anyone needs further information on this in the future.
public HttpResponse uploadFile( String teamSite,
String relativePath,
String accessToken,
File file ) throws IOException
{
String fileName = null;
HttpClient client = HttpClientBuilder.create().build();
fileName = file.getName().replaceAll( " ", "%20" );
relativePath = relativePath.replaceAll( " ", "%20" );
teamSite = teamSite.replaceAll( " ", "%20" );
HttpPost post = new HttpPost( URL );
post.setHeader( "Accept", "application/json;odata=verbose" );
post.setHeader( "Authorization", "Bearer " + accessToken );
post.setEntity( new FileEntity(file) ); //This line here
HttpResponse response = client.execute( post );
HttpEntity entity = response.getEntity();
#SuppressWarnings("unused")
String responseString = EntityUtils.toString( entity, "UTF-8" );
return response;
}

Scala HttpPost - How to pass authentication parameters

------Update
Was able to fix it by using the UsernamePasswordCredentials class
The code looks like below
val client = new DefaultHttpClient
client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("user","password"));
i am trying to make a HttpPost call to a Restful API, its expecting a username/password, how to pass those parameters? I tried 2 ways
post.addHeader("Username","user")
post.addHeader("Password","clear pwd")
and
post.addHeader("Authorization","Basic base64encoded username:password")
nothing works, I get response text as
Response Text = HTTP/1.1 401 Unauthorized [WWW-Authenticate: Digest realm="API Realm", domain="/default-api", nonce="pOxqalJKm5L5QXiphgFNmrtaJsh+gU", algorithm=MD5, qop="auth", stale=true, Content-Type: text/html; charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 311] org.apache.http.conn.BasicManagedEntity#5afa04c
Below is my code
val url = "http://restapi_url";
val post = new HttpPost(url)
//post.addHeader("Authorization","Basic QWBX3VzZXI6Q0NBQGRidHMxMjM=")
post.addHeader("Username","user_user")
post.addHeader("Password","clear pwd")
post.addHeader("APPLICATION_NAME","DO")
val fileContents = Source.fromFile("input.xml").getLines.mkString
post.setHeader("Content-type", "application/xml")
post.setEntity(new StringEntity(fileContents))
val response = (new DefaultHttpClient).execute(post)
println("Response Text = "+response.toString())
// print the response headers
println("--- HEADERS ---")
response.getAllHeaders.foreach(arg => println(arg))
Here the authorization header should be calculated like this:
httpPost.addHeader("Authorization", "Basic " + Base64.getEncoder.encodeToString("[your-username]:[your-password]".getBytes))
Instead of getUrlEncoder(), it should be getEncoder().
you can write like this, it works in my program
import java.util.Base64
httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder.encodeToString("[your-username]:[your-password]".getBytes))
DefaultHttpClient is deprecated. You should use BasicCredentialsProvider instead. Example code below:
val username = "your_username"
val password = "your_password"
val credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username, password)
)
val httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build()

How to use authentication details with a QNetWorkRequest in bb cascades?

I want to create a BB10 application using bb cascades in which i want to pass username and password to the server with a QNetWork http request. I tried the following
QNetworkRequest request = QNetworkRequest();
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
request.setRawHeader("Content-Language", "en-US");
QString concatenated = "username:password";
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
req.setRawHeader("Authorization", headerData.toLocal8Bit());
QSslConfiguration config = request.sslConfiguration();
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::TlsV1);
request.setSslConfiguration(config);
But this gives me an QNetworkReply error 202(ContentOperationNotPermittedError).What is the reason for this error? How can i solve this issue?
Thanks in Advance
This code works for me
QNetworkRequest request = QNetworkRequest();
request.setRawHeader("Authorization","Basic " + QByteArray(QString("%1:%2").arg(USER_NAME).arg(PASSWORD).toAscii()).toBase64());
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("Content-Language", "en-US");
QSslConfiguration config = request.sslConfiguration();
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::TlsV1);
request.setSslConfiguration(config);