How do I add a file into a HTTP PUT request calling the Microsoft Graph API? - microsoft-graph-api

I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.

The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");

Related

jersey client webtarget URL with non-standard encoding

Suppose the following HTTP request:
POST index.php?/api/v2/add_result_for_case/123/777
This appears in TestRail documentation at https://support.gurock.com/hc/en-us/articles/7077819312404-Results#addresultforcase
Now, I am trying to use Jersey as follows:
testRailClient()
.target(testRailUrl)
.path("/index.php")
.queryParam("/api/v2/add_result_for_case/123/777")
.request()
.post(Entity.json(...))
But, its URL gets encoded by Jersey, as follows:
https://testrail.host/index.php?%2Fapi%2Fv2%2Fadd_result_for_case%2F131143%2F131143=
Any suggestion how to make it generate the request as required by TestRail?

Jersey HTTP client content-length header

I have a kotlin classthat tryies to upload a jar file to AWS codeartifact.
val upload = client.target(to)
.request()
.header("X-Checksum-Sha1", sha1)
.header("Authorization", "Basic " + encodedAuth.toString(Charsets.UTF_8))
//.header("Content-Length", jarAsInputStream.available())
.put(Entity.entity(jarAsInputStream, MediaType.APPLICATION_OCTET_STREAM))
if (upload.statusInfo.family != Response.Status.Family.SUCCESSFUL)
throw RuntimeException("Upload failed, status=${upload.status} from=$from to=$to")
When i use it so as it is in the code snippet, the AWS codeartifact service responds with a 411 status 'content-length required'.
So i add the line (which is commented in the above snippet) .header("Content-Length", jarAsInputStream.available()) and the Jersey client throws an error Content-Length header already present
Has any of you had a similar issue? if so, how did you solve it?

How do you send MIME format emails using Microsoft Graph Java SDK?

The official documentation does not provide an example for any SDK's (including the Java SDK): https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=java#example-4-send-a-new-message-using-mime-format. As there is no example, I have tried in vain to send the MIME content using the SDK (microsoft-graph 5.0.0):
Message sending = new Message();
ItemBody body = new ItemBody();
final String mimeMessageRFC822 = input.getMimeMessageRFC822();
body.content = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
sending.body = body;
GraphServiceClient service = getService(acHost, configuration);
service
.me()
.sendMail(UserSendMailParameterSet.newBuilder().withMessage(sending).withSaveToSentItems(true).build())
.buildRequest(new HeaderOption("Content-Type", "text/plain"))
.post();
The above code sets the request's content-type to text/plain, however the request body that is being sent is JSON (xxxxxx below is a placeholder for a valid Base64 encoded MIME content string).
{
"message":
{
"body":
{
"content": xxxxxx
}
},
"saveToSentItems": true
}
The response is a 404, stating:
GraphServiceException: Error code: ErrorMimeContentInvalidBase64String
Error message: Invalid base64 string for MIME content.
I can understand why it is responding with this error as the graph endpoint is parsing the text/plain content as base64 encoded MIME but finds the JSON structure instead. I have been on a video call with a Microsoft Graph support agent, and they have seen that my MIME content is valid. Sadly, they are not able to help with the Microsoft Graph Java SDK even though it is developed by Microsoft!
This suggests that we are not supposed to use the Java SDK at all for sending MIME formatted emails. Is this correct? Surely it can't be otherwise what is the point of a library that can receive MIME formatted emails but can't send them? Does anyone have a solution?
For now at least the solution is to send a CustomRequest with MIME content instead of using the fluent API provided by the Graph client.
final String encodedContent = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
CustomRequest<String> request = new CustomRequest<>(requestUrl, service, List.of(new HeaderOption("Content-Type", "text/plain")), String.class);
request.post(encodedContent);

RestAssured - how to send a request without Content-Type?

I am using RestAssured to send a request:
Map<String, Object> headers = new HashMap<>();
headers.put("Accept", "*/*");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
Response response = RestAssured.given().baseUri(BASE_URL)
.headers(headers)
.log().all()
.post(URL_PREFIX + "/documents/request/" + username);
However, in the log I see that 1 more header was automatically added:
Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1
And I get 415 error.
Is it possible to send a request without Content-Type? I mean, without this header at all; if the request is sent with Content-Type equal to empty line, there is still a 400 error; the only way to make it work is to send the request without this header.
Seems like there is a bug in the RestAssured framework that is still open (I verified that in 4.3.3).
// https://mvnrepository.com/artifact/io.rest-assured/rest-assured
testImplementation group: 'io.rest-assured', name: 'rest-assured', version: '4.3.3'
Founded out, when creating negative tests for a API. Content type below is automatically generated when trying to send request.
Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1
Bug defined here:
https://github.com/rest-assured/rest-assured/issues/656
https://github.com/rest-assured/rest-assured/issues/986

Microsoft Graph (OneDrive) API - Resumable Upload Content-Type

I am trying to create the upload PUT request for the OneDrive API. It's the large file "resumable upload" version which requires the createUploadSession.
I have read the Microsoft docs here: As a warning the docs are VERY inaccurate and full of factual errors...
The docs simply say:
PUT
https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337Content-Length:
26Content-Range: bytes 0-25/128 <bytes 0-25 of the
file>
I am authenticated and have the upload session created, however when I pass the JSON body containing my binary file I receive this error:
{ "error": {
"code": "BadRequest",
"message": "Property file in payload has a value that does not match schema.", .....
Can anyone point me at the schema definition? Or explain how the JSON should be constructed?
As a side question, am I right in using "application/json" for this at all? What format should the request use?
Just to confirm, I am able to see the temp file created ready and waiting on OneDrive for the upload, so I know I'm close.
Thanks for any help!
If you're uploading the entire file in a single request then why do you use upload session when you can use the simple PUT request?
url = https://graph.microsoft.com/v1.0/{user_id}/items/{parent_folder_ref_id}:/{filename}:/content
and "Content-Type": "text/plain" header and in body simply put the file bytes.
If for some reason I don't understand you have to use single-chunk upload session then:
Create upload session (you didn't specified any problems here so i'm not elaborating)
Get uploadUrl from createUploadSession response and send PUT request with the following headers:
2.1 "Content-Length": str(file_size_in_bytes)
2.2 "Content-Range": "bytes 0-{file_size_in_bytes - 1}/{file_size_in_bytes}"
2.3 "Content-Type": "text/plain"
Pass the file bytes in body.
Note that in the PUT request the body is not json but simply bytes (as specified by the content-type header.
Also note that max chuck size is 4MB so if your file is larger than that, you will have to split into more than one chunks.
Goodlcuk

Resources