How to send arabic word with a http.Mutli part form data in flutter - flutter

I'm using the http package in order to send multi part - form data request to the server, it works great and the server are able to parse the files and fields, but I'm getting problem when trying to send with the request a field that contains arabic word then this field is parsed in the server as it is file.The server is unable to know that this field that contains arabic word is a field. I print the file in the server that contains the arabic word and it shows it's mimetype as 'text/plain; utf=8' but it still put it with the files. I don't know why even though I'm putting in the header
..headers['Content-Type'] = "multipart/form-data; charset=UTF-8"
var request = http.MultipartRequest('POST', postUri)
..fields['username'] = _username!
..fields['password'] = _password!
..fields['address'] = 'تشيتتشسيتش يسشتيرشتي' // Here is the problem
..headers['Content-Type'] = "multipart/form-data; charset=UTF-8"
..files.add(await http.MultipartFile.fromPath(
'coverPic',
_coverImage!.path,
contentType: MediaType('image', coverPicType),
));

Related

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

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;

Soap message encoded in base64 binary data multiple files

Recently I got a new project to work on a SOAP service and to Get and Post messages to a ASP.NET service based on xml.
The issue is that I managed to make the soap request and get the message.
The message looks like this:
UEsDBBQAAAAIAAdUe06+NXE0kR4AADLSAQALAAAAUHJvZHVzZS54bWzUXW1z48YN5k/h5EMnmbMsvomSpmkzFCXbjERJoSTb52/p9dq5mbxN2svczy/........
The message is Base64 Binary on RFC 4648 with multiple xml documents on it.
How I can construct this documents from the code in php?
The documents encrypted in this request are 3 xml files.
I managed to get them from an online decryptor called freeformatter with download function.
If I try to decode the result I get something like:
PKT{N�5q4�2�Produse.xml�]ms��
�O��C'��,����i3%یDI�$��o��ڹ��M����/�,��|vL�O�$�/�xv,,�u�s>9?;?....
Is there a solution for this?
I'm new to SOAP so I don't understand too much of it.
Thank you but i mannged to solve it.
I gonna post here the sollution so everyone who facing the same issue, get the response.
The first thing you need to do when you have an .zip file in a base64 binary string is to catch the response to a txt file.
Let's say the response from soap it's called ' $response ' and we need to catch this to an file. We do like this :
$response = $client -> _getLastResponse();
$fille = "response.xml";
fille_put_contents($fille,$response);
Now we got the response to an xml file.
The next thing to do is to get the response from xml values.
Lets say our value is <ResponseFromServer> .
`$b64 = "b64.txt";
$dom = new DomDocument();
$dom = load("response.xml");
$data = $dom->getElementByTagName("ResponseFromServer");
$catchb64 = $data;
fille_put_content($b64,$catchb64);`
Now we got the clean Base64 Binary string in one fille.
The next thing we need is to create the document ( in this case is a .zip fille)
`$input_fille = "response.txt"; // the fille with clean base64 binary data on it
$output_fille = "result.zip"; //the fille we need to create on system with the
documents decrypted
$content = fille_get_contents($input_fille); // Reading the content of input fille
$binary = base64_decode($content); // Decoding to binary
fille_put_contents($output_fille,$binary); // Writing to fille the vallues`
We dont need the ZipArchive() function, because is allready a zip archive, all we need to do is to create a empty document and after to send the binary data to it.
Cheer's and goodluck!

POST image to web service with Flutter

I am currently using Flutter and Dart to try to send an image to a web service, after which I wait for a JSON response. The below links show the Postman request that I am trying to mimic.
An image of Postman with the headers required
An image of Postman with the body
I think the issue I am having is either not setting the headers of my request correctly, or not encoding the image correctly.
Currently I am getting a HTTP 400 error.
I have tried following these suggested solutions on StackOverflow but have been getting the HTTP 400 error.
Any help would be much appreciated!
Try this. I'd suggest creating yourself a plain Dart project, if you haven't already. This way you can test things without the need of the phone emulator, etc.
main() async {
http.MultipartRequest request =
new http.MultipartRequest('POST', Uri.parse(url));
request.headers['Prediction-Key'] = '3f4a......'; // todo - insert real value
request.files.add(
new http.MultipartFile.fromBytes(
'image',
bytes,
filename: 'somefile', // optional
contentType: new MediaType('image', 'jpeg'),
),
);
http.StreamedResponse r = await request.send();
print(r.statusCode);
}
If the file is on disk, not in memory, then use the fromPath named constructor instead. Experiment with different media types. I've used image/jpeg, but you could try application/octet-stream.
As an aside, in your first screenshot you show a content type, but Postman ignores this as the overall content type is overridden by multipart-form. Uncheck that row in Postman to prove this.
There was another question recently on SO, where the server was incorrectly expecting headers to be case sensitive. In postman, try again with lowercase prediction-key to prove that the server doesn't mind lowercase headers (which is what Dart uses).

Need to find the requests equivalent of openurl() from urllib2

I am currently trying to modify a script to use the requests library instead of the urllib2 library. I haven't really used it before and I am looking to do the equivalent of urlopen("http://www.example.org").read(), so I tried the requests.get("http://www.example.org").text function.
This works fine with normal everyday html, however when I fetch from this url (https://gtfsrt.api.translink.com.au/Feed/SEQ) it doesn't seem to work.
So I wrote the below code to print out the responses from the same url using both the requests and urllib2 libraries.
import urllib2
import requests
#urllib2 request
request = urllib2.Request("https://gtfsrt.api.translink.com.au/Feed/SEQ")
result = urllib2.urlopen(request)
#requests request
result2 = requests.get("https://gtfsrt.api.translink.com.au/Feed/SEQ")
print result2.encoding
#urllib2 write to text
open("Output.txt", 'w').close()
text_file = open("Output.txt", "w")
text_file.write(result.read())
text_file.close()
open("Output2.txt", 'w').close()
text_file = open("Output2.txt", "w")
text_file.write(result2.text)
text_file.close()
The openurl().read() works fine but the requests.get().text doesn't work for the given this url. I suspect it has something to do with encoding, but i don't know what. Any thoughts?
Note: The supplied url is a feed in the google protocol buffer format, once I receive the message i give the feed to a google library that interprets it.
Your issue is that you're making the requests module interpret binary content in a response as text.
A response from the requests library has two main way to access the body of the response:
Response.content - will return the response body as a bytestring
Response.text - will decode the response body as text and return unicode
Since protocol buffers are a binary format, you should use result2.content in your code instead of result2.text.
Response.content will return the body of the response as-is, in bytes. For binary content this is exactly what you want. For text content that contains non-ASCII characters this means the content must have been encoded by the server into a bytestring using a particular encoding that is indicated by either a HTTP header or a <meta charset="..." /> tag. In order to make sense of those bytes they therefore need to be decoded after receiving using that charset.
Response.text now is a convenience method that does exactly this for you. It assumes the response body is text, and looks at the response headers to find the encoding, and decodes it for you, returning unicode.
But if your response doesn't contain text, this is the wrong method to use. Binary content doesn't contain characters, because it's not text, so the whole concept of character encoding does not make any sense for binary content - it's only applicable to text composed of characters. (That's also why you're seeing response.encoding == None - it's just bytes, there is no character encoding involved).
See Response Content and Binary Response Content in the requests documentation for more details.

URLConnection is returning text/html content type

I am trying to get the inputstream of online pdf file but the procedure not working. URLConnection is returning the content type of url as text/html instead of application/pdf. As you can see https://www.dropbox.com/s/ao3up7xudju4qm0/Amalgabond%20Adhesive%20Agent.pdf url is pdf.
I am using the following code for URLConnection and getting Content Type
URL fileUrl;
try {
String str = "https://www.dropbox.com/s/ao3up7xudju4qm0/Amalgabond%20Adhesive%20Agent.pdf"
fileUrl = new URL(str);
URLConnection connection = fileUrl.openConnection();
Log.i("mustang", "Content-type: " + connection.getContentType());
InputStream is = fileUrl.openStream();
Log.i("mustang", "is.available(): " + is.available());
Due to this, I am unable to parse the buffer. Why I am getting text/html content type?
Thanks,
Dropbox uses user-agent sniffing to determine if it should display a lightbox (preview of the PDF). What you're seeing is the lightbox code (if you printed the content you would be able to tell this).
You need to add a line specifying a non-interactive user-agent such as wget by adding a line such as:
URLConnection connection = fileUrl.openConnection();
connection.setRequestProperty("User-Agent", "Wget/5.0");
This generally overrides dropbox's smart content preview code.