The file could not be opened when request made using `NSURL` - swift2

I make a http request for the below URL :
I got below err msg:
Optional (Error Domain=NSCocoaErrorDomain code = 256)
The file image could not be opened.
File URL
code
let myURLString ="http://portal-webserver-xxx-1025638813.ap-southeast-1.xxx.amazonaws.com/smart/images/xxx.html "
let myURL = NSURL(string:myURLString)
let myHTML :NSString?
myHMTL = NSString(contentsOfURL:myURL!,encoding:NSUTF8StringEncoding)
I want to get the HTML file from the url. The code is using older swift version, what I need to use. please help.
Thanks.

Related

How to download file directly from blob URL?

I am looking to download a PDF directly from a blob URL using Ruby code. The URL appears like this:
blob:https://dev.myapp.com/ba853441-d1f7-4595-9227-1b0e445b188b
I am able to visit the link in a web browser and have the PDF appear in a new tab. On inspection, other than the GET request there are some request headers related to browser/user agent.
I've attempted to use OpenURI but it detects the url as not an HTTP URI. Open URI works just fine with files from URLs that look like https://.../invoice.pdf
I've also tried to go the JS route with this snippet but this is returning 0 for me, as others have also reported.
Any automated solutions that require a download onClick and then navigating the local disk is not sufficient for my project. I am looking to retrieve files directly from the URL in the same fashion that OpenURI works for a file on a server. Thanks in advance.
I was able to get the Javascript snippet to work. The piece that I was missing was that the blob URL needed to be opened/visited in the browser first (in this case, Chrome). Here's a code snippet that might work for others.
def get_file_content_in_base64(uri)
result = page.evaluate_async_script("
var uri = arguments[0];
var callback = arguments[1];
var toBase64 = function(buffer){for(var r,n=new Uint8Array(buffer),t=n.length,a=new Uint8Array(4*Math.ceil(t/3)),i=new Uint8Array(64),o=0,c=0;64>c;++c)i[c]='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charCodeAt(c);for(c=0;t-t%3>c;c+=3,o+=4)r=n[c]<<16|n[c+1]<<8|n[c+2],a[o]=i[r>>18],a[o+1]=i[r>>12&63],a[o+2]=i[r>>6&63],a[o+3]=i[63&r];return t%3===1?(r=n[t-1],a[o]=i[r>>2],a[o+1]=i[r<<4&63],a[o+2]=61,a[o+3]=61):t%3===2&&(r=(n[t-2]<<8)+n[t-1],a[o]=i[r>>10],a[o+1]=i[r>>4&63],a[o+2]=i[r<<2&63],a[o+3]=61),new TextDecoder('ascii').decode(a)};
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function(){ callback(toBase64(xhr.response)) };
xhr.onerror = function(){ callback(xhr.status) };
xhr.open('GET', uri);
xhr.send();
", uri)
if result.is_a? Integer
fail 'Request failed with status %s' % result
end
return result
end
def get_pdf_from_blob
yield # Yield to whatever Click actions that trigger the file download
sleep 3 # Wait for direct download to complete
visit 'chrome://downloads'
sleep 3
file_name = page.text.split("\n")[3]
blob_url = page.text.split("\n")[4]
visit blob_url
sleep 3 # Wait for PDF to load
base64_str = get_file_content_in_base64(blob_url)
decoded_content = Base64.decode64(base64_str)
file_path = "./tmp/#{file_name}"
File.open(file_path, "wb") do |f|
f.write(decoded_content)
end
return file_path
end
From here you can send file_path to S3, send to PDF Reader, etc.

How to get the downloaded xlsx file from the api endpoint in karate?

I have an endpoint that downloads an xlsx file. In my test, I need to check the content of the file (not comparing the file with another file, but reading the content and checking). I am using karate framework for testing and I am trying to use apache POI for working with the excel sheet. However, the response I get from karate when calling the download endpoint is a String. For creating an excel file with POI I need an InputStream or the path to the actual file. I have tried the conversion, but it does not work.
I guess I am missing some connection here, or maybe the conversion is bad, I am new to karate and to the whole thing.
I appreciate any help, thanks!
Given url baseUrl
Given path downloadURI
When method GET
Then status 200
And match header Content-disposition contains 'attachment'
And match header Content-disposition contains 'example.xlsx'
And match header Content-Type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
* def value= FileChecker.createExcelFile(response)
* print value
And the Java code:
public static String createExcelFile(String excel) throws IOException, InvalidFormatException {
InputStream stream = IOUtils.toInputStream(excel, Charset.forName("UTF-8"));
Workbook workbook = WorkbookFactory.create(stream);
return ("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
}
When running the scenario, I get the following error:
javascript evaluation failed: FileChecker.createExcelFile(response), java.io.IOException: Failed to read zip entry source
When testing the same endpoint in Postman, I am getting a valid excelsheet.
In Karate 0.9.X onwards you have a responseBytes variable which will be raw bytes, which may be what you need.
* def value = FileChecker.createExcelFile(responseBytes)
And you can change your method signature to be:
public static String createExcelFile(byte[] excel) {}
You should be easily able to convert a byte array to an InputStream and take it from there.
P.S. just saying that it "works in Postman" is not helpful :P
TO download zip file from Karate tests as binary bite array
Scenario: To verify and get the ADCI Uri from deployment
Given url basicURL + DeployUri +ArtifactUri
And headers {authorization:'#(authToken)',accept:'application/json',tenant:'#(tenantUUId)',Content-Type:'application/zip'}
When method get
Then status 200
And def responsebytes = responseBytes

how to make an api call to server which requires special characters using NSURL session?

I am building an iOS app with Swift2.0, XCode 7.2
I am trying to make an api call to:
htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={"locality":{"$eq":"miami"}}
let endPoint:String = "htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={%22locality%22:{%22$eq%22:%22miami%22}}"
When I try to create an URL using this string(endPoint):
let url = NSURL(string: endPoint), a nil is returned.
So I tried encoding the string before trying to create URL:
let encodedString = endPoint.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
Now the encodedString:
"htttp://xyz.com/t/restaurants-us?KEY=someKey&filters=%7B%2522locality%2522:%7B%2522$eq%2522:%2522miami%2522%7D%7D"
But now when i create a NSURL session and send the request, I get an unexpected response from the server:
Reply from server:
{
"error_type" = InvalidJsonArgument;
message = "Parameter 'filters' contains an error in its JSON syntax. For documentation, please see: http://developer.factual.com.";
status = error;
version = 3;
}
So if I don't encode the string, I will not be able to create NSURL.
But if I encode and send the request, the server is not able to handle the request.
Can anyone please suggest a workaround.
When you declare endpoint, you have already percent-encoded some characters (the quotes). When you ask iOS to percent-encode it, it percent-encodes the percent-encodes. Decoding the encodedString results in:
htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={%22locality%22:{%22$eq%22:%22miami%22}}
Instead, you should start with actual quotes in endpoint:
let endPoint:String = "htttp://xyz.com/t/restaurants-us?KEY=someKey&filters={\"locality\":{\"$eq\":\"miami\"}}"

Python 3.3 - Getting Header and redirect the results

I would like to create a script that look to a file, read each line (which are url) and fetch the HTTP header for me.
I have a questions :
I try to redirect the result to a text file but, anyhow I try, it is not working.
Can someone help me with my code please ?
import urllib.request
import sys
open('sorti.txt','w')
sorti = open("sorti.txt",'w')
print('Creation de sorti.txt')
text_file = open ("id.txt", "r")
text_file.read().strip('\n')
for lines in text_file:
urllib.request.urlopen('lines').write.sorti()
header = urllib.request.parse_http_list(lines).write.sorti()
sys.stdout(sorti)
text_file.close
sorti.close
Supposing you are looking for something like this
URL1
header_1: value
...
header_n: value
URL2
header_1: value
...
header_n: value
change the code as follows:
text_file = open ("id.txt", "r")
for line in text_file:
sorti.write(line) // writes the current url
obj = urllib.request.urlopen(line)
headers = dict(obj.info()) // gets the headers
for (h,v) in headers.items(): // write all with the specified format
sorti.write("{0}: {1}\n".format(h, v))
sorti.write("\n")
sorti.close
Those write.sorti() will not work.

Why can't I set a Stream using the FtpWebRequest.GetRequestStream() method?

I have been trying to write a simple ftp client using c# in .NET 2.0 for 3 days now and am
missing something. I I create an ftpWebRequest object and set all its properies.
string uri = host + remoteFile;
System.Net.FtpWebRequest ftp = (FtpWebRequest)(FtpWebRequest.Create(uri));
ftp.Credentials = new System.Net.NetworkCredential(username, password);
ftp.KeepAlive = false;
ftp.UseBinary = true;
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
But when I go to get the stream, it fails...
System.IO.Stream strm = ftp.GetRequestStream();
Here is the error: "System.Net.WebException: The remote server returned an error: (501) Syntax error in parameters or arguments."
This method SHOULD return the stream I need to write to and many examples do exactly this. I'm not sure what I'm missing. My host looks like this: "ftp://myhostname/" and I've triple checked my credentials.
Please help!
may be ftp.UseBinary = true; is not supported by server?
You are missing the "/" after the host:
string uri = host + "/" + remoteFile;
and the remote file string should look like this: file.txt without any path.

Resources