How to modify "Content-Disposition" in Request Content via Fiddler Script? - post

I am trying to modify "Content-Disposition" value in "multipart/form-data" POST request with Fiddler that is automatically generated by webpage's javascript with attached image on file upload.
However, I cannot find a way to do it: when I try to simply replace the "Content-Disposition" Fiddler seems to convert entire content to string, replace the Content-Disposition string and convert back to bytes, which seems to break the attached image.
Several examples of code I have tried to use:
oSession.utilReplaceInRequest("string1","string2")
var strBody=oSession.GetRequestBodyAsString();
strBody=strBody.replace("string1","string2");
oSession.utilSetRequestBody(strBody);
While these successfully replace string1 with string2, the attached image is no longer valid.
What would be a way to do it?

Related

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

Creating tempfile and removing non-image data

Been having some difficulty with an attachment issue on my site. At the moment our iOS app is pointing at an API endpoint for attachments, and sending a request similar to this:
POST /api/v2/attachments HTTP/1.1
--Boundary+0xAbCdEfGbOuNdArY
Content-Disposition: form-data; name="attachment"; filename="attachment.jpg"
Content-Type: image/jpeg
...image data...
--Boundary+0xAbCdEfGbOuNdArY--
Now, the request succeeds and the image is in fact uploaded, but it's turning out to be an invalid image because the boundary data is written to file. It basically looks like this:
file = Tempfile.new('attachment')
attachment_data = request.body.read
attachment_data.force_encoding('UTF-8')
file << attachment_data
attachment.asset = file
attachment.save!
Obviously request.body.read is including the entire request, Boundaries and all. We do actually have a stripping method that runs through each line of the file and strips out non-image data, but that's obviously not performant at all.
In an ideal world, we would just be getting the image data itself and using that to populate the tempfile, but I'm afraid I'm completely stumped about the best way to go about that.
Thoughts welcome. Thank you!

XML file generation to user specified location

I am generating a xml file using JAXB but at present file is generated at specified location,How can i use a browse button to specify the location of folder to save the generated file.
Have tried with input type="file" of HTML but it is useful for uploading the file.Want it to do from rich faces only.
Just write it directly to the HTTP response along with a Content-Disposition header with a value of attachment. This will force the browser to pop a Save As dialogue.
So, essentially all you need to do is to marshal the XML tree straight to the output stream of the HTTP response instead of the output stream of the file after having set the proper headers.
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// ...
ec.responseReset(); // Make sure the response is clean and crisp.
ec.setResponseContentType("text/xml"); // Tell browser which application to associate with obtained response.
ec.setResponseCharacterEncoding("UTF-8"); // Tell browser how to decode the characters in obtanied response.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // Tell browser to pop "Save As" dialogue to save obtained response on disk.
marshaller.marshal(model, ec.getResponseOutputStream()); // Look ma, just marshal JAXB model straight to the response body!
fc.responseComplete(); // Tell JSF that we've already handled the response ourselves so that it doesn't need to navigate.
Note: downloading a file via ajax is not possible. Remember to turn off the ajax feature of the RichFaces/Ajax4jsf command component invoking this method, if any.
See also:
How to provide a file download from a JSF backing bean?

Google docs API: can't download a file, downloading documents works

I'm trying out http requests to download a pdf file from google docs using google document list API and OAuth 1.0. I'm not using any external api for oauth or google docs.
Following the documentation, I obtained download URL for the pdf which works fine when placed in a browser.
According to documentation I should send a request that looks like this:
GET https://doc-04-20-docs.googleusercontent.com/docs/secure/m7an0emtau/WJm12345/YzI2Y2ExYWVm?h=16655626&e=download&gd=true
However, the download URL has something funny going on with the paremeters, it looks like this:
https://doc-00-00-docs.googleusercontent.com/docs/securesc/5ud8e...tMzQ?h=15287211447292764666&amp\;e=download&amp\;gd=true
(in the url '&amp\;' is actually without '\' but I put it here in the post to avoid escaping it as '&').
So what is the case here; do I have 3 parameters h,e,gd or do I have one parameter h with value 15287211447292764666&ae=download&gd=true, or maybe I have the following 3 param-value pairs: h = 15287211447292764666, amp;e = download, amp;gd = true (which I think is the case and it seems like a bug)?
In order to form a proper http request I need to know exectly what are the parameters names and values, however the download URL I have is confusing. Moreover, if the params names are h,amp;e and amp;gd, is the request containing those params valid for obtaining file content (if not it seems like a bug).
I didn't have problems downloading and uploading documents (msword docs) and my scope for downloading a file is correct.
I experimented with different requests a lot. When I treat the 3 parameters (h,e,gd) separetaly I get Unauthorized 401. If I assume that I have only one parameter - h with value 15287211447292764666&ae=download&gd=true I get 500 Internal Server Error (google api states: 'An unexpected error has occurred in the API.','If the problem persists, please post in the forum.').
If I don't put any paremeters at all or I put 3 parameters -h,amp;e,amp;gd, I get 302 Found. I tried following the redirections sending more requests but I still couldn't get the actual pdf content. I also experimented in OAuth Playground and it seems it's not working as it's supposed to neither. Sending get request in OAuth with the download URL responds with 302 Found instead of responding with the PDF content.
What is going on here? How can I obtain the pdf content in a response? Please help.
I have experimented same issue with oAuth2 (error 401).
Solved by inserting the oAuth2 token in request header and not in URL.
I have replaced &access_token=<token> in the URL by setRequestHeader("Authorization", "Bearer <token>" )

SignatureDoesNotMatch error when Content-type is 'text/*' using TAmazonStorageService.UploadObject

Using the following Delphi XE2 (update 4) code:
var
ConInfo: TAmazonConnectionInfo;
RespInfo: TCloudResponseInfo;
Service: TAmazonStorageService;
Content: TBytes;
Headers: TStringList;
begin
ConInfo:=TAmazonConnectionInfo.Create(self);
ConInfo.AccountName:='YOUR ACCOUNT NAME';
ConInfo.AccountKey:='YOUR ACCOUNT KEY';
ConInfo.Protocol:='http';
Service:=TAmazonStorageService.Create(ConInfo);
RespInfo:=TCloudResponseInfo.Create;
SetLength(Content, 128);
FillMemory(#Content[0], 128, Byte('x'));
Headers:=TStringList.Create;
Headers.Values['Content-type']:='text/plain';
if not Service.UploadObject('YOUR BUCKET', 'test.txt', Content, TRUE, nil, Headers, amzbaPrivate, RespInfo) then
ShowMessage('Failed:' + RespInfo.StatusMessage);
I always get an error on the call to UploadObject:
Failed:HTTP/1.1 403 Forbidden - The request signature we calculated
does not match the signature you provided. Check your key and signing
method. (SignatureDoesNotMatch)
This only happens when the Content-type is set to 'text/plain', 'text/html', or text anything. Using exactly the same code, if you just change the content-type to any other content-type, e.g. 'video/3gpp', then it works as expected and without error. The actual content of the object being uploaded isn't relevant and has no bearing on getting the error or not.
I've traced through the Indy code in Delphi, but I'm stumped as to why the text content type always gives this error.
Any ideas?
If you append "; charset=ISO-8859-1" to the Content-Type string, then it works:
Headers.Values['Content-type']:='text/plain; charset=ISO-8859-1';
Stepping through the code I see the Content-Type is being changed in TIdEntityHeaderInfo.SetHeaders (IdHTTPHeaderInfo.pas) which is called from TIdHTTPProtocol.BuildAndSendRequest (IdHTTP.pas).
Ultimately, it looks like the problem is that TIdEntityHeaderInfo.SetContentType (IdHTTPHeaderInfo.pas) is appending a character set to the content type if it is 'text' and it doesn't already have one. It shouldn't be changing the content type in these situations because the content type is part of the string to be signed, so changing it after the signing makes the signature invalid.
I had the very same problem. I also used application/octet-stream as content type, but still had some trouble. Later on, I discovered that bucket names have to be in lowercase (In US Standard Region, Amazon allows to define buckets with Uppercase or mixed case names; however, those buckets are not accessible through the HTTP API (including TAmazonStorageService). Instead of a not found message, I still got the 403 error (unauthenticated user).
However, one I changed the name to all lowercase, it worked fine.
Hope it helps

Resources