I am having issue with push utf8 encode message using Parse Rest, here is my body
{"where":{"$and":[{"email":{"$in":["phaxxx#gmail.com","nhungxxx#gmail.com"]}},{"deviceType":{"$in":["ios"]}}]},"data":{"alert":"TEST: Giảm 40% Khi Mua Sách Harry Potter","sound":"default","page_type":"cms_key","page_value":"harry-potter"}}
Does anyone know how to encode utf8 message?
Javascript code:
public bool SendPushNotification(string jsonContent)
{
...
request.Headers.Add("X-Parse-Application-Id", appId);
request.Headers.Add("X-Parse-REST-API-KEY", restApiKey);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
...
}
Related
I'm using Spring WebClient for getting html. The response contains polish characters such as: ą, ę, ż and so on.
After calling service i expect the response to look like this: <div>plan zajęć</div>
But the actual response looks like this: <div>plan zaj�ć</div> - and this sign replaces all polish characters.
Here's a WebClient bean config:
#Bean
WebClient webClient() {
return WebClient.builder()
.build();
}
And here's how i use it:
Optional<String> resp = webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(String.class)
.blockOptional();
And here's a link to page that i'm trying to web scrape: https://plan.polsl.pl/plan.php?winW=1000&winH=1000&type=0&id=343126158
I've no idea what to change in the WebClient configuration to get the desired effect, so I'm asking for help.
Please show how you use WebClient. I don't know Polish character but very likely your problem is related to the encoding of the response.
You can try to specify the charset to UTF_8 and see if that helps
WebClient webClient = WebClient.create();
Mono<String> response = webClient.get()
.uri(uri)
.acceptCharset(StandardCharsets.UTF_8)
.retrieve()
.bodyToMono(String.class);
String responseString = response.block();
== Updated 1/2/2023 ==
Note that Java String is using UTF-8 encoding. That's why we attempted to request the web server to return us a document in UTF-8 encoding. Unfortunately, the web server that you specified above returns ISO-8859-2 charset even though WebClient is requesting to return UTF-8 charset. You will have to transcode the response body from ISO-8859-2 to UTF-8 charset yourself. Here is the sample code to do that. I tested it with your web server.
WebClient webClient = WebClient.create();
Mono<ByteArrayResource> responseBody = webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(ByteArrayResource.class);
String responseString = new String(responseBody.block().getByteArray(), Charset.forName("ISO-8859-2"));
If you are building a generic web crawler, instead of hardcoding the above code to always transcode from ISO-8859-2 to UTF-8, you will need to get the charset information from the Content-Type header. Most of the web server would tell you the media type as well as the charset encoding in Content-Type. Then, instead of hardcoding ISO-8859-2 in the above code, you can specify the correct charset. Here is the sample code to find the charset.
WebClient webClient = WebClient.create();
Mono<ClientResponse> response = webClient
.get()
.uri("http://example.com")
.exchange();
response.map(res -> {
String contentType = res.headers().contentType().get().toString();
String charset = null;
// parse the Content-Type header to extract the charset
Matcher m = Pattern.compile("charset=([^;]+)").matcher(contentType);
if (m.find()) {
charset = m.group(1);
}
return charset;
});
Unfortunately, the web server that you specified didn't tell you the charset in Content-Type header either. In this case, you may need to look elsewhere in the response to determine the character encoding.
One place you can check is the charset attribute of the element in the HTML document. Some web servers include a element in the HTML document with a charset attribute that specifies the character encoding of the document. This is how I found out your specified document is using ISO-8859-2 charset.
WebClient doesn't have an easy way to extract the charset information from tag but you can use regular expression to extract that. Here is the sample code
WebClient webClient = WebClient.create();
Mono<String> responseBody = webClient
.get()
.uri("http://example.com")
.retrieve()
.bodyToMono(String.class);
responseBody.map(html -> {
String charset = null;
// use a regular expression to extract the charset attribute from the <meta> element
Matcher m = Pattern.compile("<meta[^>]+charset=[\"']?([^\"'>]+)[\"']?").matcher(html);
if (m.find()) {
charset = m.group(1);
}
return charset;
});
I want my bot to send a PDF file to the user. I have the PDF as a base64 string and tried to send it through an attachment:
Attachment attachment1 = new Attachment();
attachment1.Name = "name.pdf";
attachment1.ContentType = "application/pdf";
attachment1.ContentUrl = "data:application/pdf;base64," + base64String;
var m = context.MakeMessage();
m.Attachments.Add(attachment1);
m.Text = "File";
await context.PostAsync(m);
Within the emulator, it just doesn't work but in the channels Telegram and Facebook (which I need), the bot just outputs an error...
Has someone already succeed in it?
Note: Using an HTTP address works fine, but I need to use the base64 string
As this method in botframework call sendDocument method of Telegram, and this method in its document property get http url or a file_id, so you can't pass base64String to this method as a valid document type.
You can follow the valid type of the document passing into the telegram in this link (also, see the following image).
The pdf file must be embedded resource. Hope it help.
if (this.channelid == "telegram")
{
var url = string.Format("https://api.telegram.org/bot{0}/sendDocument", Settings.tokentelegram);
Assembly _assembly;
Stream file;
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(this.chat_id, Encoding.UTF8), "chat_id");
_assembly = Assembly.GetExecutingAssembly();
file = _assembly.GetManifestResourceStream("Namespace.FolderResourses.name.pdf");
form.Add(new StreamContent(file), "document", "name.pdf");
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}
I have a an Array of bytes byteArray which contains data compressed with Gzip. I want to read the whole array and decode the data using the appropriate encoding ("ISO-8859-15").
GZIPInputStream gzipInputStream = new GZIPInputStream(new MemoryStream(personalDataArray));
InputStreamReader inputStream = new InputStreamReader(gzipInputStream);
However I get a compiler error when trying to read the gzip input stream with an Input stream reader, it says cannot convert from Java.Util.Zip.GZipInputStream to System.IO.Stream. This issue does not occur in Java though. How do I get around this? How do I specify the encoding to be used too? Thanks.
You can use this method to decompress GZip, use GZipStream
Here you have Xamarin doc. about System.IO.Compression.GZipStream Class
static byte[] Decompress(byte[] data)
{
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
And you can read it using Encoding.UTF8.GetString(),
var msg = Encoding.UTF8.GetString(Decompress(personalDataArray));
Also You have to convert UTF-8 to ISO-8859-15 (Latin9), this sample is for ISO-8859-1 (Latin1), but try with ISO-8859-15.
var strISO88591= Encoding.GetEncoding("ISO-8859-1")
.GetString(Encoding.Convert(Encoding.UTF8,Encoding.GetEncoding("ISO-8859-1"), Encoding.UTF8.GetBytes(msg)));
I'm using the Microsoft Bot Framework with Cognitive Services to generate images from a source image that the user uploads via the bot. I'm using C#.
The Cognitive Services API returns a byte[] or a Stream representing the treated image.
How can I send that image directly to my user? All the docs and samples seem to point to me having to host the image as a publically addressable URL and send a link. I can do this but I'd rather not.
Does anyone know how to simple return the image, kind of like the Caption Bot does?
You should be able to use something like this:
var message = activity.CreateReply("");
message.Type = "message";
message.Attachments = new List<Attachment>();
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("https://placeholdit.imgix.net/~text?txtsize=35&txt=image-data&w=120&h=120");
string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
message.Attachments.Add(new Attachment { ContentUrl = url, ContentType = "image/png" });
await _client.Conversations.ReplyToActivityAsync(message);
The image source of HTML image elements can be a data URI that contains the image directly rather than a URL for downloading the image. The following overloaded functions will take any valid image and encode it as a JPEG data URI string that may be provided directly to the src property of HTML elements to display the image. If you know ahead of time the format of the image returned, then you might be able to save some processing by not re-encoding the image as JPEG by just returning the image encoded as base 64 with the appropriate image data URI prefix.
public string ImageToBase64(System.IO.Stream stream)
{
// Create bitmap from stream
using (System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromStream(stream) as System.Drawing.Bitmap)
{
// Save to memory stream as jpeg to set known format. Could also use PNG with changes to bitmap save
// and returned data prefix below
byte[] outputBytes = null;
using (System.IO.MemoryStream outputStream = new System.IO.MemoryStream())
{
bitmap.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
outputBytes = outputStream.ToArray();
}
// Encoded image byte array and prepend proper prefix for image data. Result can be used as HTML image source directly
string output = string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(outputBytes));
return output;
}
}
public string ImageToBase64(byte[] bytes)
{
using (System.IO.MemoryStream inputStream = new System.IO.MemoryStream())
{
inputStream.Write(bytes, 0, bytes.Length);
return ImageToBase64(inputStream);
}
}
I am generating pdf using itexsharp.
I am creating MemoryStream, then when i am trying t write MemoryStream bytes in to response but no luck. When i am executing this code in my controller the pdf not coming in response. Memory stream is populaitng correctly i can see this in debugger, but for some reason this number of butes not coming in response.
Here is my code:
HttpContext.Current.Response.ContentType = "application/pdf";
...
using (Stream inputPdfStream = new FileStream(pdfFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new MemoryStream())
{
PdfReader reader = new PdfReader(inputPdfStream);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
....
//try one
outputPdfStream.WriteTo(HttpContext.Current.Response.OutputStream); // NOT POPULATING Response
//try two
HttpContext.Current.Response.BinaryWrite(outputPdfStream.ToArray()); // NOT POPULATING Response Too
HttpContext.Current.Response.End();
}
May be some one have any ideas?
Could you not use
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Type", "application/pdf")
Response.WriteFile(pdfFilePath)
Response.End()
You should use the FileContentResult Controller.File(byte[] content, string contentType) method:
public ActionResult GeneratePDF()
{
var outputStream = new MemoryStream(); // This will hold the pdf you want to send in the response
/*
* ... code here to create the pdf in the outputStrem
*/
return File(outputStream.ToArray(), "application/pdf");
}
Source: Building PDFs in Asp.Net MVC 2.
Probably the memorystream is still set at the position after the last written byte. It will write all bytes from the current position (which is none). If you do a outputPdfStream.Seek(0) it will set the position back to the first byte, and will write the contents of the whole stream to the response output.
Anyway, like Dean says, you should just use the Reponse.WriteFile method.