I need to send a ASI http request, a post form,
when I check the body for my request it seems empty,
how to check what the body is?, why is it empty?
thanks!
- (void)sendUnsentEntries {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (!sendingEntries) {
sendingEntries = YES;
Reachability *reachability = [Reachability reachabilityForInternetConnection];
BOOL errorsSending = NO;
NSInteger unsentCount = 0;
if ([Client unsubmittedCount] > 0 && [reachability isReachable]) {
NSString *host = [self apiHost];
for (Client* clientToSend in [Client allUnsubmitted]) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#", host]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
request.requestMethod = #"POST";
[request setPostValue:clientToSend.name forKey:#"name"];
[request setPostValue:clientToSend.territory forKey:#"territory"];
NSLog(#"name:: %#", clientToSend.name);
//LOGING THE FOR THE REQUEST
NSString *requ = [[[NSString alloc] initWithData:[request postBody] encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"request body: %#", requ);
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *responseString = [request responseString];
NSLog(#"response :::%#",responseString);
if ([responseString isEqualToString:#"true"]) {
clientToSend.submitted = [NSNumber numberWithBool:YES];
}
} else {
NSLog(#"error: %#", [error description]);
}
[[self managedObjectContext] save:nil];
}
unsentCount += [Client unsubmittedCount];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:unsentCount];
if (errorsSending && showSendingErrors) {
}
}
sendingEntries = NO;
[pool release];
}
}
so I get for my
log of:: request body: an empty response,
is this the way to log the body of the form?
thanks!
The post body isn't built until the form is submitted to the server.
You have two options:
Log the post body after [request startSynchronous];
call [request buildPostBody]; before the NSLog
Related
I am facing network issue many times whenever i calling webservices.Each time it will give me error like
NSURLErrorDomain Code=-1005 The network connection was lost.
but network conenction is exist still it gives me these errors.Also this same error is too frequent.Can any one help me in this.Here is the code i am using :
- (void)postRequest:(WSPostRequestType)servicetype parameters:(NSString*)parameters customeobject:(id)object block:(ResponseBlock)block
{
if (![self isNetworkAvailable])
{
if (errorAlertView != nil)
{
errorAlertView = [[UIAlertView alloc]initWithTitle:#"AppName" message:#"Network not reachable !!" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[errorAlertView show];
}
return;
}
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/******************* Set Url for WebService ********************/
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSString *URLString = [[NSString alloc]init];
switch (servicetype)
{
case WSUserRegistration:
URLString = URLRegistraion;
break;
default:
break;
}
//NSLog(#"url String :%#",URLString);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:DEFAULT_TIMEOUT];
[request setURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:#"POST"];
NSData *postData;
// NSData *jsonData;
NSString *postLength;
if (object == nil)
{
NSString *PostParamters= parameters;
postData = [PostParamters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
}
else {
postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[object length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:object];
}
id Responceobjects;NSString *responseString;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data.length>0)
{
responseString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSDictionary *dictionary;
dictionary=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
switch (servicetype) {
case WSUserRegistration:
{
responseString=[NSString stringWithFormat:#"%#",[dictionary valueForKey:#"status"]];
Responceobjects=[dictionary valueForKey:#"data"];
}
break;
default:
break;
}
}
else if(error != nil)
{
NSLog(#" error from webservice parse line n0. 681 %#",error.localizedDescription);
if(error.code!=-1005 || ![error.localizedDescription isEqual:#"The network connection was lost."])
{
[AZNotification showNotificationWithTitle:error.localizedDescription controller:ROOTVIEW notificationType:AZNotificationTypeError];
}
}
else if(data.length == 0)
{
[AZNotification showNotificationWithTitle:#"Data Not Available..!!" controller:ROOTVIEW notificationType:AZNotificationTypeError];
}
dispatch_async(dispatch_get_main_queue(), ^(){
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ( error )
{
#try
{
[ROOTVIEW dismissViewControllerAnimated:YES completion:nil];
}
#catch (NSException *exception) {
}
block(error,Responceobjects,responseString,nil);
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}
else
{
block(error,Responceobjects,responseString,nil);
}
}];
});
});
}];
[operation setQueuePriority:NSOperationQueuePriorityVeryHigh];
[self.operationQueue addOperation:operation];
}
Here is check network available code.
- (BOOL)isNetworkAvailable
{
if([[NetworkAvailability instance] isReachable])
{
return YES;
}
else
{
return NO;
}
return NO;
}
My application mostly based on webservice data.So there are so many webservice call for different webservice.Thanks.
You have to restart content and setting like following way:
iOS Simulator -> Reset Content and Settings -> Press Reset
by using this your issue will be solve.
OR
Instead of using HTTPMethod try to use HTTPBody. After fixing this, I hope everything will fine.
Restart the simulator and check. If it didn't work reset your simulator and check.
I have a NSString which contains the URL. I want to make a GET request using the URL and also check if the response is 200.
With the current code i get response as 0.
Here is my code:
NSString *Url = #"http://www.xyx.com";
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
[req setURL:[NSURL URLWithString:Url]];
[req setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Reply = %#", req);
}]resume];
use this code it works for you:
-(void)yourMethodNAme
{
NSString *post = #"";
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:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
and finally call it in ViewDidLoad as [self yourMethodNAme];
-(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
{
[self startActivity];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
//NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
//NSLog(#"Data = %#",text);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"dictionary : %#",deserializedDictionary);
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
deserializedArr = (NSArray*)jsonObject;
NSLog(#"array : %#",deserializedArr);
}
}
[self setAlert];
}
else
{
[activityView removeFromSuperview];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[self showAlert:#"Error" :#"Network error occured." :#"Ok"];
}
}];
[dataTask resume];
}
just use the above code and call it by
[self httpGetWithCustomDelegateWithString:#"webStringHere"];
On Completion, it will call the method -(void)setAlert; so declare it in your class where you use this.
This may be due to App Transport Security blocking HTTP.
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Try making a request to a secure site (e.g. https://www.google.com) as a test.
I am sorry for this question. I am new to iOS.
I am working on xcode 7.1. I am calling a POST call on my Local server but I am getting this error. and I am not sure why. I have been trying and searching for couple of days now, but i couldn't find anything relevant. this is my code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
//create string for parameters that we need to send in the HTTP POST body
NSLog(#"My Url = %#",myUrlString);
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSLog(#"body = %#",postRequestDictionary);
NSData *json;
NSString *jsonString;
NSError *error;
// Dictionary convertable to JSON ?
if ([NSJSONSerialization isValidJSONObject:postRequestDictionary])
{
// Serialize the dictionary
json = [NSJSONSerialization dataWithJSONObject:postRequestDictionary options:NSJSONWritingPrettyPrinted error:&error];
// If no errors, let's view the JSON
if (json != nil && error == nil)
{
jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
}
}
//create a mutable HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0]; //sets the receiver’s timeout interval, in seconds
[urlRequest setTimeoutInterval:30.0f];
//sets the receiver’s HTTP request method
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:#"application/json" forHTTPHeaderField:#"Content-type"];
NSString *params = [NSString stringWithFormat:#"%#",jsonString];
NSLog(#"param = %#",params);
//sets the request body of the receiver to the specified data.
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//allocate a new operation queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
//process the JSON response
//use the main queue so that we can interact with the screen
dispatch_async(dispatch_get_main_queue(), ^{
[self parseResponse1:data];
});
}
else if ([data length] == 0 && error == nil){
NSLog(#"Empty Response, not sure why?");
}
else if (error != nil){
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Not again, what is the error = %#", error);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Please check that you are connected to internet." delegate:self cancelButtonTitle:#"I got it." otherButtonTitles: nil];
// spinnerview.hidden=YES;
[alert show];
});
}
}];
But all i am getting is this error
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLKey=http://xyz/login, NSErrorFailingURLStringKey=http://xyz/login, NSUnderlyingError=0x165a0f80 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey={url = http://xyz/login}}}}
and thing is that why is it giving "(null)"??
Please help me guys. Thanks in advance. 🙏
try after adding this key in your info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Hope this helps.
pragma mark call web service with this code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSString *mystring=[self returnMeParameterString:postRequestDictionary];
NSURL *url = [NSURL URLWithString:myUrlString];
NSData *postData = [mystring dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[mystring length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse response, NSData data, NSError *connectionError) {
if(connectionError)
{
//error
}
else
{
//success
}
}];
pragma mark convert Dictionary to string
-(NSString*)returnMeParameterString:(NSDictionary *)params{
NSMutableString *paramstring = [[NSMutableString alloc] init];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
NSMutableArray *valueArray = [[NSMutableArray alloc] init];
for( NSString *aKey in [params allKeys] )
{
[keyArray addObject:aKey];
}
for( NSString *aValue in [params allValues] )
{
[valueArray addObject:aValue];
}
for (int k=0; k< keyArray.count; k++)
{
NSString *tempString;
if(k==0)
{
tempString = [NSString stringWithFormat:#"%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
else
{
tempString = [NSString stringWithFormat:#"&%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
[paramstring appendString:tempString];
}
return paramstring;
}
Im having an issue returning 200 status code from the browser. Im trying to POST a url with the username and password to a url and get an xml response.
0 = wrong username/password
1 = success login
The correct url is :
https://apix.xxx.
incorrect url but still receiving 200 status code:
xxx.com
I believe the problem is the url not being built correctly
Even if the login is wrong i should get a 200 status code returned, but it only returns 404.
thanks for the help
- (IBAction)sigininClicked:(id)sender {
NSInteger success = 0;
#try {
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Email and Password" :#"Sign in Failed!" :0];
} else {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#/%#",
#"https://xxx.testauthenticate",
self.txtUsername.text,
self.txtPassword.text]];
NSString *post =[[NSString alloc] initWithFormat:#"%#", url];
NSLog(#"PostData: %#",post);
//NSLog(#"url: %#",url);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Sign in Failed!" :0];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
Status code 404 means that requested endpoint doesn't exist.
As I see you use link https://apix.pointstreak.com/performance/index.php/testauthenticate that is invalid. Try to open it in browser and you will see error message 404 Page Not Found.
Set correct url and it will work.
Update:
Try to change url string to this:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#/%#",
#"https://apix.pointstreak.com/performance/index.php/testauthenticate",
self.txtUsername.text,
self.txtPassword.text]];
I'm using ASIHTTPRequest [request startAsynchronous] functon to send a request to my webservice api to login. If the request is ok, it returns a json value. Then I send another request to get user's info, but here I receive an error.
Here is my code:
-(void)login
{
[usernameTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
username = [usernameTextField text];
password = [passwordTextField text];
if ( ([username length] == 0 ) || ([password length] == 0 ))
{
...
}
else
{
NSString *URL = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/Login?user=%#&pass=%#",username,password];
NSURL *requestURL = [NSURL URLWithString:URL];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestURL];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error = [request error];
if (!error)
{
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSString *unlockCode = [responseDict objectForKey:#"d"];
if ( [unlockCode isEqualToString:#"successful"] )
{
NSURL *url = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
[request startSynchronous];**//THERE IS AN ERROR**
NSError *error = [request error];
if (!error)
{
NSDictionary *responseDict = [responseString JSONValue];
NSString *realName = [responseDict objectForKey:#"RealName"];
NSLog(#"%#",realName);
}
}
else
{
//...
}
}
else
{
NSLog(#"%#",[error description]);
}
}
And there is an error:
[__NSCFString absoluteURL]: unrecognized selector sent to instance
0x69ef4b0
Another error:
void SendDelegateMessage(NSInvocation*): delegate
(_selectionLayoutChangedByScrolling:) failed to return after waiting
10 seconds. main run loop mode: kCFRunLoopDefaultMode
This line is incorrect:
NSURL *url = [NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username];
It should be changed to:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetUserInfo?user=%#",username]];