Classic ASP: Emit Response with charset UTF-16 - character-encoding

I need to do a script in classic ASP to generate a CSV file for the user to download. It needs to be encoded in "classic Windows Unicode", ie., UTF-16.
I tried this:
Response.Clear
Response.ContentType = "text/csv"
Response.Charset = "utf-16"
Response.Codepage = 1200
Response.AddHeader "Content-Disposition", "attachment; filename=export.csv"
but I get the error
ERROR -2147467259: 006~ASP 0204~Invalid CodePage Value~An invalid CodePage value was specified.
which makes sense, because according to the documentation, code page 1200 is only available to managed (ASP.NET) applications.
But then, how can I set the Response's charset to UTF-16?

Well, I “solved” it using an ADODB.Stream. The disadvantage of this is that I need to accumulate the full output in memory before I send it to the user. Basically,
dim s
set s = Server.CreateObject("ADODB.Stream")
s.Type = 2 ' text '
s.Open
do while <getting data>
s.WriteText <data>
loop
s.Flush
s.Position = 1
s.Type = 1 ' binary '
Response.Clear
Response.ContentType = "application/csv"
Response.AddHeader "Content-Disposition", "attachment; filename=export.csv"
Response.BinaryWrite s.Read
This makes use the fact that ADODB.Stream uses Unicode by default to store text.

Related

Upload Attachment to ServiceNow using SOAP and Base64 via BluePrism

I am trying to upload a file into ServiceNow using the WSDL <https://instanceName.Service-now.com/ecc_queue.do?WSDL>
I am converting the file to Base64 using Powershell. The upload via SOAPUI works fine, however the same file when downloaded is corrupted. If I upload an Excel file with data on downloading the file the Excel file is Empty
Source File Name is tp-certification-guide.pdf (Source PDF: - https://www.servicenow.com/content/dam/servicenow/other-documents/training/tp-certification-guide.pdf)
However, when I convert the file to Base64 using a portal (https://www.browserling.com/tools/file-to-base64/), I am able to upload and download the file without any issues. Again the file uploaded to ServiceNow does not get corrupted nor does it download an Empty File.
My SoapUI code: -
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ecc="http://www.service-now.com/ecc_queue">
<soapenv:Header/>
<soapenv:Body>
<ecc:insert>
<agent>AttachmentUploader</agent>
<name>problem_data.pdf:application/pdf</name>
<payload>AAAAIGZ0eXBxdCrG[..truncated..]</payload>;
<source>incident:[sysid is here]</source>
<topic>AttachmentUploader</topic>
</ecc:insert>
</soapenv:Body>
</soapenv:Envelope>
Above Code taken from https://www.servicenowguru.com/integration/sending-attachment-servicenow/
My PowerShell code is as below
$InputFile = "D:\02_Downloads\ChromeDLs\tp-certification-guide.pdf"
# Read the file as text
$Text = [System.IO.File]::ReadAllText($InputFile)
# Convert the string to UTF-8 bytes
$UTF8Bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
# Encode the UTF-8 bytes as a Base64 string
$Base64String = [System.Convert]::ToBase64String($UTF8Bytes)
$Base64String | Out-File "D:\02_Downloads\ChromeDLs\tp-certification-guide.txt"
The file should uploaded to ServiceNow using the WSDL and the same file when downloaded should not be corrupted or empty.
I feel there is something wrong in the generation of Base64 using Powershell compared to the Online Edition which would need assistance.
I can't help you with the base64 problem, but if you're interested, then here's my dotnet code to upload attachment to SNOW using REST.
Dim request As WebRequest = WebRequest.Create(REST_Address)
request.UseDefaultCredentials = True
request.Credentials = new NetworkCredential(SNOW_Username, SNOW_Password)
request.Method = "POST"
request.ContentType = ContentType
Dim byteArray As Byte() = System.IO.File.ReadAllBytes(Filename)
request.ContentLength = byteArray.Length
Dim RequestStream As System.IO.Stream = request.GetRequestStream()
RequestStream.Write(byteArray, 0, byteArray.Length)
RequestStream.close()
Dim response As WebResponse = request.GetResponse
Dim responseStream As IO.Stream = response.GetResponseStream
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd
response.Close
REST address example: https://instance.service-now.com/api/now/attachment/file?table_name=SNOWTable&table_sys_id=32charsysid&file_name=test.pdf
content type: application/pdf

Grails Base64 to PDF - render a PDF inline

I have a Grails controller action that calls a service that will return XML that contains a base64 representation of a PDF. Here is an (abbreviated) example sample.
<response status="Success"><messages/><values><pages>8</pages></values><xml/><files><pdf name="FitnessApplication" content-type="application/pdf"><![CDATA[JVBERi0xLjQKJeL ... </files></response>
After we parse that out I want to display that PDF in the browser. So far I am able to decode the string and render it using the file attribute of the render method. This serves up the PDF correctly as a download but I want it to display in the browser (inline) and NOT as a file download.
Map responseMap = new XmlParserHelper().parse( formsResponse.payload )
byte[] decoded = responseMap.files.pdf.decodeBase64()
render( file: decoded, fileName: "${document}.pdf", contentType: "application/pdf", )
I tried setting the content disposition as both an option to render and in the header map but neither seem to do the trick. Does anyone know how I can serve this PDF to the user in the browser?
Just send it in the response. But you need to add the headers on your own. E.g. something like:
response.contentType = "application/pdf"
response.contentLength = FileUtils.copyFile(pdfFile, response.outputStream)
To build on what cfrick said here is the final solution I went with.
// response data
byte[] pdfData = responseMap.files.pdf.decodeBase64()
response.contentType = "application/pdf"
response.setHeader("Content-disposition", "inline; filename='dan.pdf'")
// write to output
OutputStream output = response.outputStream
output.write(pdfData);
output.close();

Passing special characters via apache HTTPClient

I have a servlet which accepts HTML content as part of the request param. The HTML is a localized one which may be a french, spanish etc... content.
I'm also using apache HTTP client to make a request to this servlet for test purpose, which has the following header definition:
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("<URL>");
String html = FileUtils.readFileToString(inputHTMLFile, "UTF-8");
method.addParameter("html", html);
method.addRequestHeader("Accept", "*/*");
method.setRequestHeader("accept-charset", "UTF-8");
Whatever HTML is read has the character encoding utf-8, sample text:
Télécharger un fichier
However when i get the html from the request param that texts becomes T?l?charger un fichier
I went through few links such as http://www.oracle.com/technetwork/articles/javase/httpcharset-142283.html which talks about charset and how normally a browser would encode the special characters. If i were to URLEncode the html with UTF-8 and then decode that with same charset in the servlet i get the HTML as expected.
Is this the only thing i can do to preserve the charsets? Am i missing something?
Thanks.
Now that the issue with the file itself is fixed, try modifying your code as follows:
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("<URL>");
postMethod.getParams().setContentCharset("utf-8"); //The line I added
...
Note that the client needs to decode the request as UTF-8 now. French and Spanish worked correctly because their characters are included in the default ISO-8859-1 charset. Chinese characters are not. If the French and Spanish were decoded correctly on client, the client is decoding the request as ISO-8859-1, and sending UTF-8 could fail.
So you could try also adding this:
postMethod.setRequestheader("Content-Type", "application/x-www-form-url-encoded; charset=utf-8");
Just try this for post method.
HttpPost request = new HttpPost(webServiceUrl);
StringEntity str = new StringEntity(YourData);
str.setContentType("application/json");
HttpPost.setEntity(new StringEntity(str, HTTP.UTF_8));
You should better change string to base64 encoded and then send.
I think I've found the cause by examining EntityBuilder decompiled code: the EntityBuilder ignores the contentEncoding field regarding the parameters, it uses the one from contentType field. And by looking on org.apache.http.entity.ContentType the only one predefined value having UTF-8 is org.apache.http.entity.ContentType.APPLICATION_JSON.
So in my case
HttpPost method = new HttPost("<URL>");
EntityBuilder builder = EntityBuilder.create();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setContentEncoding(StandardCharsets.UTF_8.name());
...
method.setEntity(builder.build());
did the job (although I think setting contentType is redundant here).
I'm using httpclient-osgi version 4.5.4.
PostMethod method = new PostMethod("URL");
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

BinaryContent Stream wrapper in Grails

I am trying to write a simple wrapper in grails that will read a binary file from a non-public back-end web-server and makes it available as a stream to a public server.
The first question is what is the best method to handle such a solution considering that the Grails will attempt to render views by default.
I am attempting a solution which leads to an "Attempted read from closed stream." which apparently looks to avoid the view rendering by invoking response but I am not sure if this is a good solution anyway.
I am reading the back-end file through the following code:
def http = new HTTPBuilder(baseUrl)
http.request(method, ContentType.BINARY) {
uri.path = path
uri.query = query
response.success = { resp, inputstream ->
log.info "response status: ${resp.statusLine}"
resp.headers.each { h -> log.info " ${h.name} : ${h.value}" }
return inputstream
}
and later attempt to push it to the client through the following method in a controller:
def binary(){
response.outputStream << getBinaryContent("http://aaa" );
response.flush()
}
Error: "Attempted read from closed stream."
If I'm not mistaken << will close the response so response.flush() is invalid.
Here's the snippet that I use for CSV, just replace with your content type:
byte[] bytes = fileGenerated.getBytes() //fileGenerated is a File
response.setContentType("text/csv")
response.setContentLength(bytes.length)
response.setHeader("Content-Disposition", "attachment; filename=" + fileGenerated.getName())
response.outputStream << bytes

multipart http request to upload images

I m trying to use multipart post request to upload two string parameters( token and source) and an image captured from mobile device ( return jpeg encoded byte[] ). But it is generating error which I am sure is due to incorrect request.
I am still not sure about notation on creating a multipart post request. So any helpful links and resources would be good.
The code is for Blackberry java development
//------------------------------------------------------------------------------//
StringBuffer buffer = new StringBuffer();
String boundary = "--##$--";
byte[] image = byte[] from camera.getsnapshot;
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"token\"\r\n"+token+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"source\"\r\n"+"Blackberry"+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"file.jpg\";filename=\""+ "file.jpg"+"\""+"\n" + "Content- Type:image/jpeg"+"\n"+ "Content-Transfer-Encoding: binary" + boundary +"\r\n" +new String(image));
buffer.append("\r\n" + boundary + "\r\n");
String string = new String(buffer);
byte[] post = string.getBytes();
HttpConnection connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod("POST");
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,
HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA+
";boundary="+boundary);
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,String.valueOf(post.length));
connection.setRequestProperty("User-Agent", "Profile/MIDP_2.0 Configuration/CLDC-1.0");
OutputStream postStream =connection.openOutputStream();
postStream.write(post,0,post.length);
postStream.close();
\----------------------------------------------------------------------------------\
Perhaps this Nokia Community wiki page will help you: HTTP Post multipart file upload in Java ME

Resources