Here is my code
AFHTTPRequestOperationManager *opManager = [AFHTTPRequestOperationManager manager];
opManager.responseSerializer = [AFJSONResponseSerializer serializer];
[opManager.requestSerializer setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
opManager.securityPolicy.allowInvalidCertificates = NO;
opManager.securityPolicy.validatesCertificateChain = NO;
NSDictionary* parameters = #{#"phone_number":self.phoneNumberTextField.text,
#"password":self.passwordTextField.text};
[opManager POST:#"http://www.example.com:8080/api.php/login"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Login Response Object %#",responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Login2222-2 - %#",error);
}];
Here is my error
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred
and a secure connection to the server cannot be made."
UserInfo={_kCFStreamErrorCodeKey=-9836,
NSLocalizedRecoverySuggestion=Would you like to connect to the server
anyway?, NSUnderlyingError=0x28185ce40 {Error
Domain=kCFErrorDomainCFNetwork Code=-1200 "An SSL error has occurred
and a secure connection to the server cannot be made."
UserInfo={NSErrorFailingURLStringKey=https://www.example.com:8080/api.php/login,
NSLocalizedRecoverySuggestion=Would you like to connect to the server
anyway?, _kCFNetworkCFStreamSSLErrorOriginalValue=-9836,
_kCFStreamPropertySSLClientCertificateState=0, NSLocalizedDescription=An SSL error has occurred and a secure
connection to the server cannot be made., _kCFStreamErrorDomainKey=3,
NSErrorFailingURLKey=https://www.example.com:8080/api.php/login,
_kCFStreamErrorCodeKey=-9836}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made.,
NSErrorFailingURLKey=https://www.example.com:8080/api.php/login,
NSErrorFailingURLStringKey=https://www.example.com:8080/api.php/login,
_kCFStreamErrorDomainKey=3}
Normal for the first time login.For the second time, these error is indicated.
Related
I'm working on an iOS App and I'm consuming Documentum REST services. Till now all "GET" Service part is working fine all data properly responded from server. But Now I need to do some "POST" part to upload Document files to server.
But I got stuck in Error from server.
So following code I'm using to upload Document files to server and also Provided Detailed Error Message.
Code:
(IBAction)btnPostDocumentToServer:(id)sender {
NSString *filePath=[[NSBundle mainBundle] pathForResource:#"demotpcode" ofType:#"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:filePath];
[self postMultipart:#"http://devser1:9090/dctm-rest/repositories/Mobile/folders/0b03445d800bfa1f" fileName:#"temCodeiOS" file:pdfData progress:nil params:nil];
}
(void)postMultipart: (NSString*) url fileName: (NSString*)name file:(NSData*) fileData progress:(UIProgressView*) progressView params:(NSDictionary*) parametersDictionary {
NSDictionary *meta = #{#"properties":#{#"r_object_type": #"ecr_attachment", #"document_id": #"0903445d80210726",#"object_name": #"temCodeiOS.pdf",#"a_content_type":#"pdf",#"subject":#"new Doc from iOS Device"}}; //#{#"propreties": #{#"object_name": name}}; // You can modify this part to add more detail.
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:[[NSUserDefaults standardUserDefaults] stringForKey:#"username"] password:[[NSUserDefaults standardUserDefaults] stringForKey:#"password"]];
NSMutableURLRequest *request=[manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:url parameters:parametersDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:metaData name:#"metaData" fileName:#"metaData" mimeType:#"application/json"];
[formData appendPartWithFileData:fileData name:#"binary" fileName:name mimeType:#"text/plain"];
} error:nil];
NSURLSessionUploadTask *uploadTask; // Create resumable task
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
[progressView setProgress:uploadProgress.fractionCompleted]; //Update the progress view
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
}
Detail ERROR:
Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSUnderlyingError=0x600000056350 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/vnd.emc.documentum+json" UserInfo={com.alamofire.serialization.response.error.response= { URL: http://devser1:9090/dctm-rest/repositories/Mobile/folders/0b03445d800bfa1f } { status code: 400, headers {
Connection = close;
"Content-Type" = "application/vnd.emc.documentum+json;charset=UTF-8";
Date = "Thu, 15 Dec 2016 06:46:20 GMT";
Server = "Apache-Coyote/1.1";
"Transfer-Encoding" = Identity;
} }, NSErrorFailingURLKey=http://devser1:9090/dctm-rest/repositories/Mobile/folders/0b03445d800bfa1f, com.alamofire.serialization.response.error.data=<7b227374 61747573……>, NSLocalizedDescription=Request failed: bad request (400)}
I'm using Xcode 8.1, iOS 10.1 Simulator and AFNETWorking 3.0. Please Help me to understand this and guide me as I'm using AFNETWorking First time. Thanks in advance.
You are using wrong Content-Type value when calling Documentum REST service:
"Request failed: unacceptable content-type: application/vnd.emc.documentum+json"
I didn't use Documentum REST apart from Documetnum xCP 2.X, but in all cases application/json was the right Content-Type (I'm no saying it'll work, just check out what your service is expecting).
Use NSURLSession call api on https server not worked on ios9, worked on ios8
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.example.com/api"]];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *sessionTask = [urlSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(#"----: %#", error);
} else {
NSLog(#"-------: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
When run on simulator or device, on device before iOS9, i'll get right response.
But when run on iOS9+, will get
CFNetwork SSLHandshake failed (-9824)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fda12f29830 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://www.example.com/api, _kCFStreamErrorDomainKey=3}
I have tried some methods
Disable ATS in plist file
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Add NSExceptionDomains
use command nscurl --ats-diagnostics https://www.example.com to test server connection, All configuration return FAIL
Any suggestion?
Thanks
Im working in an app where you suscribe to a multicast socket to listen to other devices that post to that socket. When listening everything is working fine. The problem is when I try to post to that socket in a local network. It says "Network unreachable" and I can't send the data. My code is like this.
PORT 5775
SOCKETADDRESS #"225.4.5.6"
Listener
self.socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
if (![self.socket bindToPort:PORT error:&error])
{
NSLog(#"Error binding to port: %#", error);
return;
}
if(![self.socket joinMulticastGroup:SOCKETADDRESS error:&error]){
// NSLog(#"Error connecting to multicast group: %#", error);
// return;
}
if (![self.socket beginReceiving:&error])
{
NSLog(#"Error receiving: %#", error);
return;
}
Client(Sender)
self.udpSender = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
if (![self.udpSender bindToPort:BRD_PORT error:&error])
{
NSLog(#"Error binding to port: %#", error);
return;
}
if(![self.udpSender enableBroadcast:YES error:&error]){
// NSLog(#"broadcast s%#", error);
//return;
}
And I try to write like this.
[self.udpSender sendData:input toHost:SOCKETADDRESS port:PORT withTimeout:-1 tag:0];
This codes work when I have internet access. But when I connect to a local network the sender says "Network is unreachable". I don't know what I'm doing wrong. Hope you can help me. Thanks.
I am using afnetworking in my application.
To post data on server I wrote following code
- (void) callLoginAPI:(NSDictionary *)dictProfile{
// 1
NSDictionary *params = #{#"username":[dictProfile valueForKey:#"name"],
#"first_name":[dictProfile valueForKey:#"first_name"],
#"last_name":[dictProfile valueForKey:#"last_name"],
#"email":[dictProfile valueForKey:#"email"],
#"dob":[dictProfile valueForKey:#"birthday"],
#"gender":[dictProfile valueForKey:#"gender"],
#"location":[[dictProfile valueForKey:#"location"] valueForKey:#"name"],
#"timezone":[dictProfile valueForKey:#"timezone"],
#"language":#"",
#"profile_pic_url":[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?type=large",[dictProfile valueForKey:#"id"]],
#"cover_pic_url":#""
};
NSString* HOST_URL = [NSString stringWithFormat:#"%#login/",BASE_URL];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
[operationManager POST:HOST_URL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"resp:%#",responseObject);
// Enter what happens here if successsful.
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"error:%#",error);
// Enter what happens here if failure happens
}];
}
But in response I got following error
error:Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x7cc8bb50 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ca9d4d0> { URL: http://10.1.81.35:8000/api/login/ } { status code: 500, headers {
"Content-Type" = "text/html";
Date = "Tue, 07 Oct 2014 08:25:40 GMT";
Server = "WSGIServer/0.1 Python/2.7.6";
Vary = Cookie;
"X-Frame-Options" = SAMEORIGIN;
} }, NSErrorFailingURLKey=http://10.1.81.35:8000/api/login/, NSLocalizedDescription=Request failed: internal server error (500),
I don't understand where I made mitake.
Any help would be appriciable.
I think you're ok. Your server returns an error to your request. Code 500 usually means internal error such as unhandled exception. So it definitely has nothing to do with client.
I tried to GET html from Apple homepage.
AFHTTPRequestOperationManager *manager
= [AFHTTPRequestOperationManager manager];
[manager GET:#"http://www.apple.com/jp" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTML: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This failed with error message as below:
2014-02-07 14:54:22.922 Tests[1833:70b] Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x8a32650 {NSErrorFailingURLKey=http://www.apple.com/jp/, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xea2e1a0> { URL: http://www.apple.com/jp/ } { status code: 200, headers {
"Accept-Ranges" = bytes;
"Cache-Control" = "max-age=237";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 4402;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Fri, 07 Feb 2014 05:52:51 GMT";
Expires = "Fri, 07 Feb 2014 05:56:48 GMT";
Server = Apache;
Vary = "Accept-Encoding";
Via = "1.0 proxy1.screen.co.jp (squid)";
"X-Cache" = "MISS from proxy1.screen.co.jp";
"X-Cache-Lookup" = "HIT from proxy1.screen.co.jp:8080";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
I found the message Request failed: unacceptable content-type: text/html so I understand I have to let text/html acceptable. Then, I added the line: manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];.
AFHTTPRequestOperationManager *manager
= [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes
= [NSSet setWithObject:#"text/html"]; // ###### ADDED LINE ######
[manager GET:#"http://www.apple.com/jp" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTML: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But this failed, too.
2014-02-07 14:55:48.927 Tests[1873:70b]
Error: Error Domain=NSCocoaErrorDomain Code=3840
"The operation couldn’t be completed. (Cocoa error 3840.)"
(JSON text did not start with
array or object and option to allow fragments not set.)
UserInfo=0xfa7b870 {NSDebugDescription=
JSON text did not start with
array or object and option to allow fragments not set.}
Thank you for your help.
The problem is that AFHTTPRequestOperationManager defaults to a responseSerializer of AFJSONResponseSerializer. By changing acceptableContentTypes, you are changing which content types will be accepted, but you're not changing the fact that AFJSONResponseSerializer will still look for JSON in the response.
You might want to just set the responseSerializer to AFHTTPResponseSerializer, so that it will no longer try to parse the JSON (and will automatically accept text/html):
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
I just tried with wget, and ending with "jp" gave a 301 redirect.
Try ending it with "jp/".