This is my current call to (asmx) SOAP web service:
NSString *soapMessage =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<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/\">"
"<soap:Body>"
"<Save xmlns=\"http://www.myapp.com/\">"
"<par1>%i</par1>"
"<par2>%#</par2>"
"<par3>%#</par3>"
"</Save>"
"</soap:Body>"
"</soap:Envelope>", par1, par2, par3
];
NSURL *url = [NSURL URLWithString:#"http://....asmx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if([self.delegate respondsToSelector:#selector(myAppHTTPClientDelegate:didUpdateWithWeather:)]){
[self.delegate myAppHTTPClientDelegate:self didUpdateWithWeather:responseObject];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([self.delegate respondsToSelector:#selector(myAppHTTPClientDelegate:self:didFailWithError:)]){
[self.delegate myAppHTTPClientDelegate:self didFailWithError:error];
}
}];
[operation start];
But I need to change this to use AFHTTPSessionManager.
I suppose that I need to use this:
[operation POST:<#(NSString *)#> parameters:<#(id)#> constructingBodyWithBlock:<#^(id<AFMultipartFormData> formData)block#> success:<#^(NSURLSessionDataTask *task, id responseObject)success#> failure:<#^(NSURLSessionDataTask *task, NSError *error)failure#>]
But I am not clear about what parameters should I set?
UPDATE
NSDictionary *s_request = #{#"par1": [NSString stringWithFormat:#"%i", par1], #"par2": par2, #"par3": par3, #"par4": [NSString stringWithFormat:#"%i", par4], #"par5": par5};
AFHTTPSessionManager* s_manager = [[AFHTTPSessionManager alloc] init];
[s_manager POST:#"http://192.168.10.26/mywebservice/myservice.asmx?op=MethodName" parameters:s_request success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"DONE!");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"FAILED %#, %#", [error localizedDescription], [error localizedFailureReason]);
}];
This code always fail. Getting error 500. Do I just need to add method URL or I need to add complete soap message somewhere. What I miss here?
You need to pass parameter in Dictionary like in the following example:
NSDictionary *request = #{#"email": self.email.text, #"password": self.password.text};
[manager POST:login parameters:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"DONE!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed to log in: %#", operation.responseString);
}];
Related
i am working on get api when hit the api in app i am not getting updated response when i remove the app from simulator and device its working fine.guys what i am doing wrong please help me.i have already tried Afnetworking simple Api nsurl session.
NSString *strURL = [NSString stringWithFormat:#"https://mysponsers.com/m/comments/publicpost/674"];
NSURL *url = [NSURL URLWithString:strURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
[httpClient getPath:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"RESPONSE--->1%#",json);
} failure:^(AFHTTPRequestOperation* operation, NSError *error) {
//fail!
NSLog(#"Error String is %#", error.localizedDescription);
}];
Here is the code i am using afnetworkikng for hitting the api.
Thank You
You can try with latest version of AFNetworking library or you can simply use this code also.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://mysponsers.com/m/comments/publicpost/674"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
}
}];
[dataTask resume];
You can install or update AFNetworking via cocoapods by adding this (pod 'AFNetworking', '~> 3.1.0') in your pod file.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
// Change your api content-type here:
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
[manager GET:#"{ Write your url here }"
parameters:nil
progress:nil
success:^(NSURLSessionDataTask *operation, id responseObject) {
NSString *response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Success response: %#", response);
}
failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"Failure response: %#", response);
}];
I need to integrate SMS Verification using Twilio url.
I have ACCOUNT_SID,AUTH_TOKEN and url but not able to parse using Objective C.
CODE:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSString *post = [NSString stringWithFormat:#"From='number'To=%#&Body=message %d to verify your mobile number.",txt_otp.text,[[self sms_verification_code]intValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twilio.com/2010-04-01/Accounts/(SID)/SMS/Messages"]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *authStr = [NSString stringWithFormat:#"SID:TOKEN"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"SMS verification%#",responseDictionary);
}
}] resume];
I have succeeded parsing using AFNetworking SDK.
NSString *kTwilioSID = #"sid";
NSString *kTwilioSecret = #"token";
NSString *kFromNumber = #"";
NSString *kToNumber =#"";
NSString *kMessage = [NSString stringWithFormat:#"message %d",[[self sms_verification_code] intValue]];
NSString *urlString = [NSString
stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages/",
kTwilioSID, kTwilioSecret,kTwilioSID];
NSDictionary*
dic=#{#"From":kFromNumber,#"To":kToNumber,#"Body":kMessage};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"application/xml"];
[manager POST:urlString parameters:dic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"success %#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
completion:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Why I can't pass test? Any blocks of AFHTTPRequestOperation not called. Seems that expectFutureValue don't wait results and returns immediately. I trying on XCode 6.1 and Kiwi 2.3.1
Thanks!
context(#"AFNetworking", ^{
it(#"stubs a request with an error", ^{
NSError *error = [NSError errorWithDomain:#"com.luisobo.nocilla" code:123 userInfo:#{NSLocalizedDescriptionKey:#"Failing, failing... 1, 2, 3..."}];
stubRequest(#"POST", #"https://example.com/say-hello").
withHeaders(#{ #"X-MY-AWESOME-HEADER": #"sisisi", #"Content-Type": #"text/plain" }).
withBody(#"Adios!").
andFailWithError(error);
NSURL *url = [NSURL URLWithString:#"https://example.com/say-hello"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"sisisi" forHTTPHeaderField:#"X-MY-AWESOME-HEADER"];
[request setHTTPBody:[#"Adios!" dataUsingEncoding:NSASCIIStringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
__block BOOL succeed = NO;
__block BOOL failed = NO;
__block NSError *capturedError = nil;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
succeed = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
capturedError = error;
failed = YES;
}];
[operation start];
[[expectFutureValue(theValue(failed)) shouldEventually] beYes];
});
});
Im trying to post with an array as the post instead of a dictionary. However i get an error:
Incompatible pointer types sending NSMutableArray to parameter of type NSDictionary
Here is the code
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
How can I post JUST the arrays contents?
Update:
This code works, but I would prefer to get the answer below working as its cleaner and af handles the serialization. Im guessing the request body is different, but how do i see what the body is?
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.com/resources.json"]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
I am assuming you want foo and bar to be your parameters without any values? if so you will want to do something like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:#[[NSNull null], [NSNull null]] forKeys:parameters];
[manager POST:#"http://example.com/resources.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT
Try adding
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:#"abcd",#"UID", nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://xyz:8080/cde"] ];
[request setHTTPMethod:#"POST"];
[request setValue:dict forHTTPHeaderField:#"parameter"];
[request setValue:#"get-employee-details" forHTTPHeaderField:#"serviceName"];
//[request setValue:#"pk703s" forHTTPHeaderField:#"ATTUID"];
AFHTTPRequestOperation *oper = [[AFHTTPRequestOperation alloc]initWithRequest: request] ;
[oper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(#"response STring: %# ", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure");
NSLog(#"response: %#", operation.responseString);
NSLog(#"erro: %#", error.description);
}];
[oper start];
Unable to send the parameter throught the request object.
If i dont send the parameter then i am unable to call the service
you're adding post value in your header.
NSMutableString *postString = #"myPostValue=value";
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
If you still have problem, check from server side what you get