Sending a Word document over HTTP Post in Business Central without OnPrem scope - ms-word

I need to be able to send a Word document over HTTP POST in Business Central. It needs to be sent to an Azure Function that takes in two Word documents.
How would I go about uploading the Word documents to Business Central (I Assume through UploadIntoStream) and then sending the files over HTTP?

You are correct, you need to upload the file into a stream and send it over HTTP. Depending on your azure function you need to either base64 encode it or send it as a binary. This should help you on your way.
The below is mockup code that tells you how to insert an uploaded file into a HTTP request but it does not contain a fully working, authenticated HTTP request. That depends on you Azure Function setup.
procedure SendUploadedFileToAPI() result: JsonObject
var
Base64Convert: Codeunit "Base64 Convert";
Instr: InStream;
jObject: JsonObject;
Client: HttpClient;
Response: HttpResponseMessage;
Content: HttpContent;
ContentHeaders: HttpHeaders;
UploadFilename: Text;
SelectFileLbl: Label 'Select a file';
CannotConnectErr: Label 'Cannot connect';
begin
UploadIntoStream(SelectFileLbl, '', 'All files (*.*)|*.*', UploadFilename, InStr);
// Use a json with base64
jObject.Add('file', Base64Convert.ToBase64(Instr));
Content.WriteFrom(Format(jObject));
Content.GetHeaders(ContentHeaders);
ContentHeaders.Clear();
ContentHeaders.Add('Content-Type', 'application/json');
// Or send as binary
Content.WriteFrom(Instr);
ContentHeaders.Add('Content-Type', 'application/json');
if not Client.Post('url', Content, Response) then
Error(CannotConnectErr);
end;

Related

How to read Gzipped payload in a POST request in SpringBoot

I need to read gzipped json payload in a POST request in my SPringBoot app which accepts json data. How to do that in order to keep the application generic as there may be other clients in future sending data in plain json or other compression formats? I suppose this should be handled by the server itself so is there any way to instruct the embedded Tomcat to unzip the payload?
My SpringBoot application runs on embedded Tomcat 9.0.17.
The controller accepts JSON payload in a POST request.
#RequestMapping(value = "/update/v1", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public ResponseEntity<String> receiveUpdates(#RequestBody String update) {
We recently changed our content provider and the new one is sending payload in "gzip" format (with header content-encoding=gzip) and without any content-type header. As a result it gives the following error
'error': 'Unsupported Media Type', 'message': "Content type '' not supported"
If I change my consume type to MediaType.ALL_VALUE, my controller starts receiving the request but the payload itself is gzipped. I can handle it in my service layer but that would make it specific to gzipped data.
This problem could be solved by introducing a Filter to handle gzipped payload as mentioned here and here.
But I believe there should be a way to instruct the Tomcat to handle this and serve unzipped data.

Files are uploading to Google drive with Untitled name in Delphi

I am trying to upload files to Google drive using
RestAPI in Delphi.Every thing is working fine but files are Uploading into Google drive with Untitled name.
Below is code i written for uploading into drive.
local_filename:= 'D:/Capture.jpg';
{$ENDIF}
RESTResponseDataSetAdapter.AutoUpdate :=false;
RESTRequest.Params.Clear;
RESTRequest.Method := TRESTRequestMethod.rmPOST;
RESTRequest.AddParameter('application/json; charset=utf-8','{"title": "Capture.jpg"}',TRESTRequestParameterKind.pkREQUESTBODY);
RESTClient.BaseURL := 'https://www.googleapis.com/upload/drive/v2';
RESTRequest.Resource := '/files?uploadType=multipart';
upload_stream := TFileStream.Create(local_filename,fmOpenRead);
upload_stream.Position := 0
RESTRequest.Addbody(upload_stream, TRESTContentType.ctIMAGE_JPEG);
RESTRequest.Execute;
Can some one suggest how to give a file name/ upload the file with the same name to google drive.
AddBody() appears to supercede AddParameter(), so you would be wiping out your metadata JSON. This is stated in the AddBody() documentation:
Generally, a call to AddBody replaces any previous value of the body parameter. However, if you pass ABodyContent as a string, the specified value is appended, and the resulting request contains several body parameters
The JSON metadata and the JPG file need to be sent together in the request body, in multipart/related format. However, looking at TRESTRequest, I don't see an easy way to send requests in that format (I may be wrong here). You might have to put the entire multipart data in a single TStream and pass that to AddBody() with a ContentType of TRESTContentType.ctMULTIPART_RELATED. If you try to add the various pieces as separate parameters, it won't send the right content type:
A single-parameter request uses application/x-www-form-urlencoded, while a multiple-parameter request uses multipart/mixed instead.
Check Google Drive REST API reference
https://developers.google.com/drive/v2/web/manage-uploads#multipart.
You have to send "metadata". There are 2 options. You complete that simple upload and then call another request to update metada of this file. Or you can do multi-part upload and add a parameter.
This one should work but it seems that REST request does not support this method.
RESTRequest.Method := TRESTRequestMethod.rmPOST;
RESTRequest.Params.AddItem('metadata', '{"title": "YourFileName.dat"}', TRESTRequestParameterKind.pkREQUESTBODY, [], TRESTContentType.ctAPPLICATION_JSON);
So the solution is to update metadata after your request
var
s: string
RESTRequest1.Response.GetSimpleValue('id', s);
RESTRequest1.Params.Clear;
RESTClient1.BaseURL := 'https://www.googleapis.com/drive/v2/files/'+s;
RESTRequest1.Resource := '';
RESTRequest1.Method:=TRESTRequestMethod.rmPUT;
RESTRequest1.AddBody('{"title": "Capture.jpg"}', TRESTContentType.ctAPPLICATION_JSON);
RESTRequest1.Execute;

Sending Files and Metadata in Jersey Rest Service

I need to create a ReST service using Jersey 2.0. I need to send multiple documents and metadata to the client.
What is the best approach do to the achieve this.
I was able to send a MultiPart response from the server , but not sure how to read this from the client code
Let's say you have a document called "document1" which you want to get via your client.
In your REST-API your unique identifier for the document (the resource) could be:
http://example.com/restapi/documents/document1
As you want to READ data you do a HTTP-GET Request to that uri.
And here comes the important part for you: A resource can have multiple representations - meta data and binary data in your case.
So the client has to tell the server which representation type to get (content negotiation). This information can be set in the ACCEPT Header of the client request for instance.
You can use the content type "application/json" as a representation for the meta data.
Unfortunately you didn't tell us what kind of binary data you want to send.
If they are PDFs the content type would be "application/pdf" for instance. If the binary data doesn't have a specific type you can use "application/octet-stream".
Of course there is work to be done on the server side too. Here an example:
#Path("/documents/{documentname}")
public class docResource {
#GET #Produces("application/json")
public Response getDocumentMetaData(#PathParam("documentname") String docName) {
// Create a Response containing a json
}
#GET #Produces("application/pdf")
public Response getDocumentBinaryData(#PathParam("documentname") String docName) {
// Create a response containing the binary data
}
...
}
Jersey will check the accept header of the client and will run the appropriate method.
Also see: https://jersey.java.net/documentation/latest/jaxrs-resources.html
If you are using jersey with jackson you can also easily marshal a POJO to JSON and visa versa:
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
If you are not sure what to do in the "getDocumentBinaryData"-Method - checkout this simple example from mkyong:
http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/

POSTa Request with rest assured api using XML Payload

I am in need of one requirement.I want to POST a request using Rest Assured API using XML payload,I did not get any where how to set the body using XML. any one please tell me how I can achieve this.
I have one table customers with 5 fileds,name,id,address,email and phone number.My URL to post the request is something like
"http://com.myproject.app:8080/MyApp/SchmaName/customers".Please any one help me out.Thanks in advance
The above should work, here it is again in a slightly different version with your example...
Response response = given().
contentType("application/xml").
body(myXML).
when().
post("http://com.myproject.app:8080/MyApp/SchmaName/customers");
myXML would be the xml you want to send (5 fields; name,id,address,email and phone number). After that you can pull the result from response.
You can just post in the request body as a String, InputStream, byte[] or a Java object (that will be serialized to XML using JAXB). For example:
String myXML = ..
given().contentType(ContentType.XML).body(myXML).when().post("/x").then(). ..

nodejs, redis and mailparser wont parse an email

I am using mailparser by andris(https://github.com/andris9/mailparser). I am sending an email via redis to an nodejs app. The mailparser for somereason is unable to parse it. What could be causing the issue?
The code to get the email from redis. client is an instance of node_redis Client. MailParser is andris' mailparser. The email in redis is sent via another server, to whose channel i have subscribed. The email sent, when saved in a text file and parsed using andris' test.js, gives the expected output.
client.subscribe('email1');
client.on('message', function(channel, message){
var Parser = new MailParser();
Parser.on('headers', function(headers){
console.log(headers.addressesTo[0].address);
});
Parser.feed(message);
Parser.end();
});
I found the reason for this. The input I saw receiving had \r\n converted to \n
Instead of
Parser.feed(message);
I believe you want
Parser.write(message);
I couldn't find the feed method in the documentation. I am using the write function and it's working. The message is the original unaltered email message, including headers, body, and attachments.