Using POST for flight API - ios

I have been trying to implement the Wego flights API from http://support.wan.travel/hc/en-us/articles/200191669 which uses HTTP POST requests. I've only really ever used GET requests, so I did some reading on POST and so far I have not been able to find a way to post a request with a dictionary of flight data (in objective-c) as shown in the link above:
POST api.wego.com/flights/api/k/2/searches
{
"trips": [
{
"departure_code": "SYD",
"arrival_code": "LON",
"outbound_date": "2014-01-24",
"inbound_date": "2014-01-29"
}
],
"adults_count": 1
}
Do I have to create the NSDictionary myself and then (assign?) it to the request, or is there a way to format the dictionary into a string? Thanks in advance for any help :)

You have to create the POST data as follows:
NSDictionary *trips = [NSDictionary dictionaryWithObjectsAndKeys:
#"SYD", #"departure_code",
#"LON", #"arrival_code",
#"2014-01-24", #"outbound_date",
#"2014-01-29", #"inbound_date",
nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:
trips, #"trips",
#"1", #"adults_count",
nil];
NSError *jsonError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&jsonError];
And then make the POST request:
NSURL *url = [[NSURL alloc] initWithString:#"http://api.wego.com/flights/api/k/2/searches"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
[urlRequest setHTTPMethod:#"POST"];
const char *parameters = [jsonData bytes];
NSData *postData = [[NSData alloc] initWithBytes:parameters length:strlen(parameters)];
[urlRequest setHTTPBody:postData];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&requestError];
NSLog(#"%#", [NSString stringWithUTF8String:[data bytes]]);

Related

NSJSONSerialization get error "index 1 beyond bounds for empty array"

sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

Bad formatting: Add JSON data to existing URL

I need to send request like this:
"http://api.site.com/login?q={"meta":{"api_key":"cb2f734a14ee3527b3"},"request":{"id":"username#host.name","password":"passw0rd"}}`
...the response to which should look like {"id":399205,"token":"d43f8b2fe37aa19ac7057701"} To do so, I have tried the following code:
self.responseData = [NSMutableData data];
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:#"cb2f734a14ee3527b3" forKey:#"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:#"tc-d#gmail.com",#"id", #"abc",#"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, #"meta", idPasswordDict, #"request", nil];
NSURL *url = [NSURL URLWithString:#"http://api.site.com/login?="];
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
self.recievedData = [NSMutableData data];
}
Later on, I get in the following:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.recievedData appendData:data];
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
The response data comes back as "<h1>CHttpException</h1><p>wrong sign</p>" As I understand, the way of adding json data to the current url is not appropriate in this case. Does anyone have advice on how I can fix this?
resolve my problem. Convert posted json to appended string to base url-string. that's how I did it:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *dictString = [[NSMutableString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
[dictString insertString:#"http://api.site.com/login?q=" atIndex:0];
//don't know why but dictString contains a lot of #"\n" and spaces to present it nice-formated.
[dictString replaceOccurrencesOfString:#"\n" withString:#"" options:nil range:NSMakeRange(0, dictString.length)];
[dictString replaceOccurrencesOfString:#" " withString:#"" options:nil range:NSMakeRange(0, dictString.length)];
NSURL *url = [NSURL URLWithString:[dictString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if it helps someone will appreciate tick near this issue=)
You can do it right using AFNetworking library - it's easy to implement and to work with. Whole code you need in this case is quite simple and it was always working well for me.
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:#"cb2f734a14ee3527b3" forKey:#"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:#"tc-d#gmail.com",#"id", #"abc",#"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, #"meta", idPasswordDict, #"request", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *urlString = #"http://api.site.com/login";
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:jsonString, #"q", nil];
NSURL *url = [NSURL URLWithString:urlString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:nil parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//OK
NSLog(#"%#", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
//Response failed
}];
[operation start];

How to reach members of json with iOS

I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.

i have issues in posting a json object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
NSString *username = #"user";
NSString *password = #"password";
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSLog(#".....%#....",dictionnary);
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://abcd.com/SVCs/WSUserService.svc/MobSignIn";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
NSString *responseString = [[NSString alloc]
initWithData:responseData
encoding:NSASCIIStringEncoding] ;
NSLog(#"%#", responseString);
I want to post a json object that has username and password to the web service.. but it gives a vague output.. can anyone help me on this
Output:
2013-05-14 18:50:17.155 UWUI[6226:11303] .....{
"user_email" = user;
"user_password" = password;
}....
2013-05-14 18:50:18.233 UWUI[6226:11303] 
**
followed by a xml format content
**
NSString *UN = #"user";
NSString *PWD = #"password";
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:UN forKey:#"UN"];
[dictionnary setObject:PWD forKey:#"PWD"];
NSLog(#"dictionnary...%#", dictionnary);
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://abcd.com/SVCs/WSUserService.svc/MobSignIn";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);
Set the content type may solve your issue. Add the given code to your request before sending,
[request addValue:#"application/json" forHTTPHeaderField:#"Content-type"];

Resources