SocketRocket - Invalid Sec-WebSocket-Accept - ios

When trying to connect to a custom socket server using SocketRocket I am getting the error:
Error Domain=SRWebSocketErrorDomain Code=2133 "Invalid Sec-WebSocket-Accept response" UserInfo=0x8f6af00 {NSLocalizedDescription=Invalid Sec-WebSocket-Accept response}
I have linked this back to the _checkHandshake method in _HTTPHeadersDidFinish. The _checkHandshake method is doing the following:
NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept")));
I have found this question and have the latest version of socketrocket but doesn't seem to be working?
https://github.com/square/SocketRocket/issues/24
Please let me know how I get around this error (SocketRocket - Invalid Sec-WebSocket-Accept)

I confirm that (using a SockJS server) by changing this:
NSURL *url = [NSURL URLWithString:#"http://localhost:9090"];
to this:
NSURL *url = [NSURL URLWithString:#"http://localhost:9090/websocket"];
the error was gone.

Related

AWS API SDK provides invalid URL

I created an API using AWS and generated the SDK for iOS use. However, when I try to call the API, I get this error.
Error occurred: Error
Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo={NSUnderlyingError=0x1546a36b0{Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=(null)https://(api-path),...}
The URL is hard-coded in the SDK and does not have any sort of (null) in the string. I have no clue where this is coming from.
Replacing the following code in the AWS-generated init(configuration: AWSServiceConfiguration) worked for me:
Original:
if let endpoint = configuration.endpoint {
self.configuration.baseURL = endpoint.URL
}
Replace by:
self.configuration.baseURL = URL(string: URLString)
I don't understand why it says the endpoint is nil even though it has successfully been created immediately beforehand. Anyway, it might help you solve the issue.
Check your NSURL object to see if it is nil when you init it from NSString.
Then check your url in NSString to see if it contains any white spaces, which make your url invalid.
To solve that you have to add this to your url:
NSString *yourUrl; // Your url in NSString type.
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encoded];
To those who downvoted my answer:
If you downvoted because it wasn't written in swift, I just tried my best to help.
Just because I don't have experience with swift programming, doesn't mean I have to stop helping others to solve their problems.

Properly escaping characters for AFNetworking 2.0 URL string

I have a api which needs to use a url string in order to work (wouldn't work with the normal NSDictionary request). The string I'm trying to use is
http://10.1.10.25:8181/config?param={"obj":["hours"]}
However, the following code which I used to escape the characters does not work. It returns a bad url error. What is the proper way to escape characters here?
NSURL *url = [NSURL URLWithString:#"http://10.1.10.25:8181/config?param={\"obj\":[\"hours\"]}"];
// Error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x8ca3780 {NSUnderlyingError=0x8ca6980 "bad URL", NSLocalizedDescription=bad URL}
Below is a picture of a working example using a online REST service.
In this case you just need to encode your param like this:
http://10.1.10.25:8181/config?param=%7B%22obj%22%3A%5B%22hours%22%5D%7D

initWithContentsOfURL returns nil only in iOS 5.x [duplicate]

I have been stuck with this for a while and don't seem to get around this.
I am trying to read the contents of an URL as a string from an URL, But i get a weird
Error -> Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
My code :
fetchedString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"www.example.com/iphone"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",fetchedString);
// if there is something wrong with the URL
if (error) {
NSLog(#"Error -> %#", error);
return ;
}
What am I doing wrong? I tried using getting as NSData as well, but I get null back.
Yes, the URL is missing the scheme: "http://".
"Error -> Error Domain=NSCocoaErrorDomain Code=256"
For the error code check the Apple documentation:
NSError codes in the Cocoa error domain.
NSFileReadUnknownError = 256,
NSFileReadUnknownError
"Read error, reason unknown"
Not that the error definition is very helpful. :-)
Also do not check if error is nil to determine if there is an error, check the return value for nil. error is not guaranteed to be nil on successful execution.
I had a similar problem accessing files located on my device. I followed NSURL isFileURL always returns NO
and used [NSURL fileURLWithPath] instead of [NSURL URLWithString] - this worked!
I got this error (Error Domain=NSCocoaErrorDomain Code=256) as soon as our ssl certificate expired. that may not help you but could help someone else.
Sandboxing
If you're using sandboxing in your app, you might want to check that com.apple.security.network.client is set to YES. It's in the the General tab of your Target in Xcode 5 under
Network: Outgoing Connections (Client)
Also be aware that if you see a code 257 when trying to reach a file:/// url, that's also probably because of sandboxing, but this time rather the File Access part. Because I didn't want to open it to anything else than `com.apple.security.files.user-selected.read-write'
User selected files
I preferred to use A Dead Simple Fileserver and use http://localhost:3000 when in Debug mode.
More reasons that might be causing this specific error:
SSL is misconfigured on the server
The server redirects (301) the http URL to https (see #1)
App transport security also uses this code for blocked requests.
I got the same error. The above marked answer is perfect. But in my case, I had the "http://" in the url but had to add the port number in the url request since there is a service running on a specific port that is actually responding to your request.
#"http://example.com:8084/yyy.zzz"
I got the same error, the above solution didn't work for me, in my case i was calling dataWithContentsOfURL from within a UNNotificationServiceExtension so i had to update the info.plist file of the UNNotificationServiceExtension with the app transport security entries.

ios - Restkit and SSL certificate error

I have a tomcat server that uses a self signed SSL certificate and is running a web service. I am trying to connect to the web service with Restkit. However, I am getting an error related to certificate validity. Here is my code:
NSURL *url=[NSURL URLWithString:baseURL];
RKClient *client = [RKClient clientWithBaseURL:url];
client.disableCertificateValidation=YES;
RKRequest *request = [client requestWithResourcePath:[NSString stringWithFormat:#"/addEvent?deviceID=%#&eventID=%#",deviceID,eventID]];
request.disableCertificateValidation=YES;
request.delegate=self;
RKResponse *response = [request sendSynchronously];
This request fails with the following error:
2013-01-09 15:11:53.931 Mobile_ACPL[5761:907] The certificate for this server is invalid. You might be connecting to a server that is pretending to be “notify.acpl.lib.in.us” which could put your confidential information at risk.
I get this error even though I have set disableCertificateValidation to YES. How can I get this working?
EDIT: I attempted adding the certificate as shown here: https://github.com/RestKit/RestKit/pull/131
I still get the same result.
EDIT 2: It looks like the error message is being set at this line in RKRequest.m:
payload = [NSURLConnection sendSynchronousRequest:_URLRequest returningResponse:&URLResponse error:&error];
NSURLConnection does not cater for authentication challenges in synchronous calls. You need to make asynchronous calls for this to work.
In my case, I was setting disableCertificateValidation on RKClient but I was using a RKObjectManager which used a different RKClient. The following line, placed after the RKObjectManager initialization, did the trick:
[RKObjectManager sharedManager].client.disableCertificateValidation = YES;
if you are using RestKit using
client.allowsInvalidSSLCertificate = YES;
won't work, instead do this:
if you added rest kit manually to your project, click on RestKit.xcodeproj go to project > Build Settings > Preprocessor Macros
and add _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_=1
thats finished.

SSErrorDomain error code 109. NewsStand download from Amazon S3

While downloading a file from Amazon S3 in iOS. Intermittently NSURLConnectionDownloadDelegate's method didFailWithError: get called and this is what I got when I logged received NSError object
Error Code: 109
Error Domain: SSErrorDomain
Error Description: "Cannot connect to .s3.amazonaws.com"
Searched all the Apple documentation, StackOverflow and other sites but not found anything on this. Today I raised a technical query to Apple also for this using my developer account.
Any idea ?
Update:
So after looking into HTTP response error code (403 Forbidden), I got the idea. It is because of "RequestTimeTooSkewed" error from S3 (The difference between the request time and the current time is too large.). I cross checked it by changing iPad's/Mac's system time by 1 hour and this error is coming immediately now, even for a small (200kb) file.
Now as suggested in many blogs I am first making a HEAD request to AWS as below to get the Date string and not passing the system Date
NSString *awsURL = #"http://s3.amazonaws.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:awsURL]];
[request setHTTPMethod:#"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];
NSString *dateString = nil;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
dateString = [[response allHeaderFields] objectForKey:#"Date"];
}
return dateString;
and setting this as Date header in NSMutableURLRequest
[urlRequest setValue:awsDateString forHTTPHeaderField:#"Date"];
This request I am adding to my issue for download
NKAssetDownload *nkAssetDownload = [nkIssue addAssetWithRequest:urlRequest];
Still the same error !!!! It now more crazier than my last situation.
Anyone ?
Update 2
I was able to make request successfully (even the system clock of my iPad is incorrect) by replacing "GMT" with "+0000" in the date string.
Update 3
Still some requests fail with same error which is weird, but I am assuming it is something the NewsStand Framework is messing up.
So it is RequestTimeTooSkewed error and the above code to fetch date from S3 server's head response to add in request does the trick.

Resources