ASIHTTPRequest not connecting using proxy parameters in iOS 5 - objective-c

The error code I'm receiving:
Error Domain=ASIHTTPRequestErrorDomain Code=1 "A connection failure occurred" UserInfo=0x6993280 {NSUnderlyingError=0x6d520c0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 306.)"
I do not have option but ASIHTTPRequest. I have already developed the app and cannot use the any alternatives.
Currently we are using iOS version 5.1.1
I have developed the app one year back with the same code for iOS 3 and it was working properly. Now same code is failed to work. I suspect this happens with the latest iOS versions.
This code works well without proxy settings but not with proxy settings.
_method = [NSStringstringWithFormat:#"http://%#%#", _settings.ServerLocation, _settings.WebServicePath];
NSLog(_method);
NSString *soapMessage = [NSStringstringWithFormat:#"%#%#%#",
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n",
parameters,
#"</soap:Body>\n"
"</soap:Envelope>\n"];
//NSLog(#"soapMessage : %#",soapMessage);
NSURL *url = [NSURLURLWithString:_method];
ASIHTTPRequest *request = [ASIHTTPRequestrequestWithURL:url];
if(_settings.IsProxy)
{
[request setProxyHost:_settings.HostIP];
[request setProxyPort:(NSInteger)_settings.Port];
}
constchar *utfString = [soapMessage UTF8String];
NSMutableData *req = [NSDatadataWithBytes:utfString length:strlen(utfString)];
[request addRequestHeader:#"Content-Type"value:#"text/xml; charset=utf-8"];
[request addRequestHeader:#"Content-Length"value:[NSStringstringWithFormat:#"%d", [soapMessage length]]];
[request addRequestHeader:#"SOAPAction"value:action];
if(_settings.IsProxy)
{
[request addRequestHeader:#"Host"value:_settings.HostIP];
}
[request setPostLength:[soapMessage length]];
[request setRequestMethod:#"POST"];
[request setPostBody:req];
[request setTimeOutSeconds:5];
[request setNumberOfTimesToRetryOnTimeout:1];
if(_settings.IsProxy)
{
if([_settings.Usernamelength] > 0)
{
[request setProxyUsername:_settings.Username];
}
if([_settings.Passwordlength] > 0)
{
[request setProxyPassword:_settings.Password];
}
}
//[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];

I have downloaded the ASIHTTPRequest Libraries and it worked as i expected.
before it works, i have removed below line of code
[request addRequestHeader:#"Host"value:_settings.HostIP];

Related

Network requests are failing - NSURLSession - App Sandbox - Xcode 9

I have a simple GET request that I am trying to run in my macOS application. However I keep getting the following error:
A server with the specified hostname could not be found.
The URL I am trying to download JSON data from is:
https://suggestqueries.google.com/complete/search?client=safari&q=mercedes
If I test it in my browser or in an online API tester website (such as Hurl.it), the request works fine. A JSON file is then downloaded automatically.
However running the request via my macOS app does not work. Here is my code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://suggestqueries.google.com/complete/search?client=safari&q=mercedes"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"Data: %#", data);
NSLog(#"Response: %#", response);
NSLog(#"Error: %#", error);
}] resume];
Here is the full error log:
dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
dnssd_clientstub ConnectToServer: connect() failed
path:/var/run/mDNSResponder Socket:6 Err:-1 Errno:1 Operation not
permitted 2017-10-27 09:58:31.610493+0100 search suggestions
[] nw_resolver_create_dns_service_locked
DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
TIC TCP Conn Failed [1:0x600000164080]: 10:-72000 Err(-65563)
Task <12212C3B-8606-49C2-BD72-AEBD575DB638>.<1> HTTP load failed
(error code: -1003 [10:-72000])
Task
<12212C3B-8606-49C2-BD72-AEBD575DB638>.<1> finished with error - code:
-1003
Data: (null)
Response: (null)
Error: Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified
hostname could not be found." UserInfo={NSUnderlyingError=0x60400004fa20 {Error
Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)"
UserInfo={_kCFStreamErrorCodeKey=-72000,
_kCFStreamErrorDomainKey=10}}, NSErrorFailingURLStringKey=https://www.suggestqueries.google.com/complete/search?client=safari&q=mercedes,
NSErrorFailingURLKey=https://www.suggestqueries.google.com/complete/search?client=safari&q=mercedes,
_kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, NSLocalizedDescription=A server with the specified hostname could not
be found.}
What am I doing wrong? It's just a simple GET request, I don't understand why the data won't load.
I figured out what was wrong, even though I had set Allow Arbitrary Loads to YES, this is no longer enough to enable network requests.
There is a new setting in Xcode 9 called App Sandbox that can stop incoming/outgoing network connections too! I had to turn this setting off and then all network requests started to work.
In XCode 11.5 I had to check these two flags
You have to turn off the "App Sandbox".
Go to:
xcode Project-> Capabilities -> App SandBox
Please try below code
#property (nonatomic, strong) NSURLConnection *connection;
NSMutableString *urlString = [NSMutableString stringWithString:BASE_URL];
[urlString appendFormat:#"%#",apiName]; //apiName —> Webservice Name
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setValue:#"gF!DeEfFrjqaAaD$gH#Mn#w(z" forHTTPHeaderField:#"PC-API-KEY"]; //Optional Parameter pass if required key
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"]; //if your required Get than [request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[parameterDict toJSON]];
[request setTimeoutInterval:45.0];
self.connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (self.connection) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
self.downLoadedData = [NSMutableData data];
}

How do I POST JSON data object to server iOS8?

I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 8. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
How can I send the below format to server???
{"createFrom":"","createType":"","filename":"AC","filter":"","lstData":[{"FieldName":"LNK_RELATED_CN","FieldValue":""},{"FieldName":"LNK_RELATED_CO","FieldValue":""},{"FieldName":"MLS_PURPOSE","FieldValue":"Inquiry"},{"FieldName":"MLS_STATUS","FieldValue":"Open"},{"FieldName":"MMO_NOTES","FieldValue":""},{"FieldName":"DTE_NEXTACTIONDATE","FieldValue":""},{"FieldName":"MMO_NEXTACTION","FieldValue":""}],"password":"Infodat2","username":"manmeets","IsNew":true}
I have seen code like this:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:#"%#AssetSave",[defaults objectForKey:#"siteAddress"]]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
_responseData = [NSMutableData data];
NSLog(#"request : %#", request);
_nsurlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
But I really don't know how to send a JSON object to a server using a POST method at all. Could anybody please help me out?
The code you have is fine, you just need to create jsonData:
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
(thought you should really also include an &error so you can see what's happening if something goes wrong)

NSURLConnection POSTing JSON data to ASP.Net WebAPI not returning a response

I am currently posting json data using an asynchronous NSURLConnection to a ASP.Net WebAPI resource. The connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: is being called, and the correct amount of data is being written. But the connection:didReceiveResponse:, connection:didReceiveData: or connectionDidFinishLoading: are not being called, but eventually it gives up, and the connection is lost.
I am setting up the connection as follows:
NSURL *url = [[NSURL URLWithString:[Common baseUrl]] URLByAppendingPathComponent:#"api/iCat/wishlists/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
NSString *jsonString = [self generateStrippedJsonForWishlist:wishlist];
NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
And initiating the connection with:
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Eventually the request will time out with a "The network connection was lost" error message. To me it seems like the app is never completely finished writing the body of the message.
From the api side, the method is never actually being called (break point is not being hit). But if I send the request with no body, then it does.
I have tested the same call using curl, and it is working as expected:
curl -v -i -X POST -H "Content-Type: application/json" -d '{"CreatedBy":"iPad Simulator","ContactName":"Ddd","ContactEmail":"ddd","Products":[{"ProductId":117,"ProductName":"Internal doors - deco","Specification":""}]}' http://SCMOBILE02:1861/api/iCat/wishlists/upload
Try library https://github.com/AFNetworking/AFNetworking while posting json data.
Can you try the following code below ?
-(void) post
{
NSString * a = #"{company_name : \"com\"}";
NSString * URL = #"yourUrl";
NSString *post = [NSString stringWithFormat: #"%#",a];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setTimeoutInterval:20.0];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
In your web api you should have the following class and post method like below
public class company
{
public string company_name { get; set; }
}
// POST api/values
public void Post([FromBody]company value)
{
var t = value;
}

How to POST NSData on server using MKNetworkKIt

Currently our application is using ASIFormDataRequest to post data on server.
I was using
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlWeb];
[request setShouldPresentAuthenticationDialog:NO];
[request addRequestHeader:#"User-Agent" value:#"ASIHTTPRequest"];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"text/xml; charset=utf-8"];
[request addRequestHeader:#"SOAPAction" value:#"http://something"];
[request setUsername:#"ABC"];
[request setPassword:#"XYZ"];
[request setDomain:#"LMN"];
[request appendPostData:[strSoapEnvl dataUsingEncoding:NSUTF8StringEncoding] ];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request setNumberOfTimesToRetryOnTimeout:2];
[request startAsynchronous];
BUT ASIHTTPRequest is not supporting ARC. So I have decided to use MKNetworkKIt as replacement. But I am not getting any sample code to do the same.
I have seen downloaded code from github of Mugunth Kumar but there they used NSMutableDictionary object as parameter in MKNetworkOperation.
For SOAP, you should use something like this.
[op setCustomPostDataEncodingHandler:^NSString *(NSDictionary *postDataDict) {
DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:[rootElement XMLString]
options:0
error:nil];
return [doc XMLString];
} forType:#"text/xml"];
NSDictioanry is for JSON, or URL or x-plist encoding which are infact the most common encoding types.

How to escape all special chars before encoding a string used in a simple http post -objective-c

I'm building a request that will be a simple http POST. Inside this post I need to add a few items and one of these is a large viewstate string that is pulled down during a previous request. What I've noticed is that the raw request needs to have all special chars escaped (like the below)
_EVENTTARGET=&_EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUENTM4MQ9kFgJmD2QWAmYPZBYCZg9kFgJmD2QWAgIBEGRkFgQCAQ9kFgICBw9kFgJmD2QWCmYPFgIeA3NyYwUpL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtcmVudG9ubGluZS5wbmdkAgEPFgIfAAUlL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtc3BhY2VyLnBuZ2QCAg8WAh8ABSUvYXNzZXRzL2ltYWdlcy9zaXRlbWFpbm5hdi1tb3ZpZXMucG5nZAIDDxYCHwAFJS9hc3NldHMvaW1hZ2VzL3NpdGVtYWlubmF2LXNwYWNlci5wbmdkAgQPZBYCZg9kFgZmDxYCHwAFLi9hc3NldHMvaW1hZ2VzL3NpdGVtYWlubmF2LWtpb3Nrc2Fub255bW91cy5wbmdkAgEPFgIfAAUlL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtc3BhY2VyLnBuZ2QCAg8WAh8ABSgvYXNzZXRzL2ltYWdlcy9zaXRlbWFpbm5hdi1idXlPbmxpbmUucG5nZAICD2QWAgIBD2QWAgIGD2QWAgIBD2QWAmYPZBYCAgIPEA8WAh4EVGV4dAVTUmVjb2duaXplIG1lIGZvciAxNCBkYXlzIChEbyBub3QgY2hlY2sgdGhpcyBib3ggaWYgeW91IGFyZSB1c2luZyBhIHNoYXJlZCBjb21wdXRlcilkZGRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBVVjdGwwMCRjdGwwMCRjdGwwMCRjdGwwMCRNYWluQ29udGVudCRNYWluQ29udGVudCRNYWluQ29udGVudCRiYnhsb2dpbl83JGNoa1JlY29nbml6ZU1lNZH1xfrz8glwi2XmQJFTCJ0dMNk%3D&
But I'm not certain that I've done this in objective-c. Currently when I NSLog out the viewstate string it is still showing / and = characters.
Can anyone verify I'm on the right path here? And if not how would I convert the special chars in viewstate (ie - instead of = I should get %3D)?
- (void)doHttpPostWithViewState:(NSString *)viewstate
{
responseData = [[NSMutableData data] retain];
NSURL *url = [NSURL URLWithString:#"https://localhost/Login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString* theBodyString = [[NSString alloc] initWithFormat:#"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%#",viewstate];
NSData *requestData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[request setAllHTTPHeaderFields:headers];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And finally, for local debugging purposes- how can I use NSLog to view the final (raw) string that will be sent to the client? Thank you in advance!
Update
Turns out this is a bug in the stringByAddingPercentEscapesUsingEncoding method
I've found the following to work from this blog post
NSString * cleanViewState = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)viewstate,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
You're probably looking for the stringByAddingPercentEscapesUsingEncoding: method on NSString to %-encode your POST request.
Update:
If the NSString method isn't getting all the special characters you need, the next step is to drop down to the Core Foundation level function (CFURLCreateStringByAddingPercentEscapes), which gives you better control. See http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/