Unable to send the parameter to a Web Service in objective C - objective-c

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

Related

How to check JSON post return value

I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link

How to create and post json to web service Objective c

I try to convertNSDictionary to JSON data and sent it to PHP.server in "POST" request with setHTTPBody.
I received a null from the server when I sent from my app, but when I send the JSON from PostMan I receive the objects.
Where am I wrong ?
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSString *url = [NSString stringWithFormat:#"http://myAddress/sql_service.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSArray *arrayOfStrings = #[#"alex",#"dima"];
NSDictionary *dict = #{#"request_type" : #"select_with_params",
#"table" : #"user",
#"where" : #"f_name=? OR f_name=?",
#"values" : arrayOfStrings};
NSData* jsonData1 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
[request setHTTPBody:jsonData1];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (data)
{
[receivedData appendData:data];
}
else
{
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error = nil;
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(#"connectionDidFinishLoading");
}
this is the json i need to post.
{
request_type: "select_with_params",
table: "user",
where: "f_name=? OR f_name=?",
values: ["dima", "alex"]
}
jsonData1 is not nil.
the data in didReceiveData is :
Try AFNetworking
EDIT
NSString *url = [NSString stringWithFormat:#"http://myAddress/sql_service.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSArray *arrayOfStrings = #[#"alex",#"dima"];
NSDictionary *dict = #{#"request_type" : #"select_with_params",
#"table" : #"user",
#"where" : #"f_name=? OR f_name=?",
#"values" : arrayOfStrings};
NSData* jsonData1 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
[request setHTTPBody: [[NSString stringWithFormat:#"%#", jsonData1] dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
if (responseObject)
{
NSLog(#"Success!");
}} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error");
}];
[op start];
Hope this helps

expectFutureValue fails

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];
});
});

How to convert AFNetworking service invoke to use AFHTTPSessionManager

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);
}];

AFNetworking POSTing malformed JSON - single quotes and [Object] refs

I am using AFNetworking and I am trying to POST a JSON structure. The problem is that instead of something like {"my_property":"my value"}, it's formatting it as {my_property:'my_value'}. I guess the loss of the first set of quotes is OK in most cases, but I'm not sure what to do with the non-JSON single quotes and am pretty confused as to why it would generate single quotes at all given that it knows it's creating JSON from an NSDictionary. Additionally, it's including [Object] refs where I would just expect a "{". This is what the server is getting:
...
num_matches: 32,
view_instance: properties_in_view: [Object],
[ { view_instance_ctr: 0, view_id: '4e5bb37258200ed9aa000011' },
...
The target is iOS 5.0, so I'm assuming it's using NSJSONSerialization to create JSON (although I haven't tried to verify this yet). The dictionary I send validates to JSON with isValidJSONObject. If I print out the serialized version, it looks great. The simplified version of the code looks like:
NSDictionary *params = myDictionaryThatValidatesToJSON;
httpClient.parameterEncoding = AFJSONParameterEncoding;
NSMutableURLRequest *request = [httpClient
requestWithMethod:#"POST" path:#"" parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation start];
I'm hoping there's a bigDummy = NO flag I'm missing.
I think your issue is on the server side - ie. the debug you've quoted in your question is not the raw JSON text received by the server, but some reinterpretation of this that some component on the server has done.
Michael is correct. By using his code of data i'm using this to perform POST request with JSOn parameter :
// dataDictionary is your parameter dictionary
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:NSJSONWritingPrettyPrinted error:&error];
//NSString *jsonOut = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:webURL]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"Webservice URL"
parameters:nil];
NSMutableData *body = [NSMutableData data];
[body appendData:jsonData];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];