NSString *urlString = #"http://chkdin.com/dev/api/peoplearoundmexy/?";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *parameterString=[NSString stringWithFormat:#"skey=%#&user_id=%#",#"XXXXXXX",#"3225"];
NSLog(#"%#",parameterString);
[request setHTTPMethod:#"POST"];
[request setURL:url];
[request setValue:parameterString forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);
This is my json parsing, my problem is when I am hit this api it is showing
{
message = "Valid skey required.";
status = 0;
}
But this api is working in safari.i am think is the problem is for request adding to url wrong. can you help me please....
i got response through AFNetworking 3
try this
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://chkdin.com/dev/api/peoplearoundmexy/?" parameters:#{#"skey":#"sa6rw9er7twefc9a7dvcxcheckedin",#"user_id":#"3225"} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
}];
i tried following code without AFNetworking and its working fine.
NSString *post = [NSString stringWithFormat:#"skey=%#&user_id=%#",#"sa6rw9er7twefc9a7dvcxcheckedin",#"3225"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://chkdin.com/dev/api/peoplearoundmexy/?%#",post]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:nil];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);
Related
I have used POST method to call API with header values and params for body on my application.
The server only accepts forms in the format
"form": {
"action" : "login",
"user" : "311"
},
When we use code
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSString *params = [self makeParamtersString:parameters withEncoding:NSUTF8StringEncoding];
NSData *jsonData2 = [params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
My form looks like this
form = {
action = login;
user = 311;
};
Can you produce the result you want?
Could you please help me to solve this issue.
Try
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: parameters options:0 error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
How about change the parameters like this.
NSDictionary *parameters = #{#"form":#{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
Try This if you need base64 encoding
NSMutableDictionary *param = [#{#"form":#{#"action": #"login", #"user": #"311"}} mutableCopy];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:serviceURL];
NSString *strEncoded = [self encodeParameters:param];
NSData *requestData = [strEncoded dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestData];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)requestData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Function encodeParameters
+(NSString *)encodeParameters:(NSDictionary *)dictEncode
{
// Encode character set as per BASE64
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"/+=\n"] invertedSet];
NSMutableString *stringEncode = [[NSMutableString alloc] init];
NSArray *allKeys = [dictEncode allKeys];
for (int i = 0;i < allKeys.count; i++) {
NSString *key = [allKeys objectAtIndex:i];
if([dictEncode valueForKey:key])
{
[stringEncode appendFormat:#"%#=%#",key,[[dictEncode valueForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:URLBase64CharacterSet]];
}
if([allKeys count] > i+1)
{
[stringEncode appendString:#"&"];
}
}
return stringEncode;
}
Try this
NSURL * url = [NSURL URLWithString:#"%#",url_string];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSDictionary * paramters = [NSDictionary dictionaryWithObjectsAndKeys:#"login",#"action",#"311",#"user", nil]; // [NSDictionary dictionaryWithObjectsAndKeys:#"value",#"key", nil];
NSDictionary *params = #{#"form": paramters};
NSError *err = nil;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
Try this,
NSString *parameters = #"\"form\":{\"action\" : \"login\", \"user\" : \"311\"}";
NSData *jsonData2 = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
NSError *error;
NSDictionary *parameters = #{#"form": #{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted error:&error];
request.HTTPBody = jsonData
//Using NSURLSession is better option than using NSURLConnection
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#", respondData);
} else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
Try AFNetwoking
NSString *urlString = [NSString stringWithFormat:#"URL"];
NSDictionary *para= #{#"action": #"login", #"user": #"311"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Hi I am new to ios post method.In my app i want to show list of values.
The request format is:
{"customerId":"000536","requestHeader":{"userId":"000536"}}
The code i used is:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
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/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error){
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}
];
The response is : (null)
How to request the values with same format as shown above?Thanks in advance.
Use This Code
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
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/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err)
{
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}];
[task resume];
i want to convert this code to AFNetworking but i have a error. i used
AFNetworking POST to REST webservice this code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *latest_url = #"url_string";
[request setURL:[NSURL URLWithString:latest_url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:useragent_string forHTTPHeaderField:#"User-Agent"];
[request setValue:host_string forHTTPHeaderField:#"Host"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Connection"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Proxy-Connection"];
[request setTimeoutInterval:30.0];
[request setHTTPBody:postData];
NSError *errorx = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&errorx];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonerror;
NSData *get_data_from_request = [ourdelegate do_request:request_url post_array:request_post_array debug:istekdebug];
NSArray *statuses =[NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &jsonerror];
How to convert this code to AFNetworking?
Since you are using post request, here's what you can do with AFHTTPSessionManager. You can also call AFHTTPSessionManager Get method with block invocation.
NSURL *baseURL = [NSURL URLWithString:BaseURLString];
NSDictionary *parameters = #{#"Host": host_string};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"yourFile.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog("handle succes");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog("handle error %#",[error localizedDescription]);
}];
Have fun :)
Since you aren't being specific with the error like rckoenes mentioned above.......
Why don't you just go get PAW from LuckyMarmot
It helps you formulate REST api calls and will translate the request into AFNetworking for you. Phenomenal tool for only $19.99. Worth every penny.
I am able to get the JSON Response in iOS code through POST Request only when the parameters are empty. Response from Server is { Token = "" }
NSString *postData = [NSString stringWithFormat:#""];
But when I add any parameters like shown below, I get 400 status code as response.
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
The interesting thing is the same parameters work in REST Client perfectly and gets a response. And also works in Android code too. In android a JSON object is created then these key value pairs are added to the JSON object
JSONObject jsonObj = new JSONObject();
jsonObj.put("userName", "apple#test.com");
jsonObj.put("deviceCode", "Dev455");
jsonObj.put("pwd", "225");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httppost.setEntity(entity);
and request and then receives the correct response.
Can anyone suggest me the equivalent code for iOS for the above Android code?
My present code is
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSLog(#"post:%#",postData);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSLog(#"post:%#",[postData dataUsingEncoding:NSUTF8StringEncoding]);
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
User AFNetworking and improt the following in your class
#import "AFNetworking.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPRequestOperation.h"
Use the following code to for Post request:
- (void)sendPOSTRequest {
NSArray *keys = [NSArray arrayWithObjects:#"userName",#"deviceCode",#"pwd",nil];
NSArray *objects = [NSArray arrayWithObjects:#"apple#test.com",#"Dev455",#"225", nil];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[manager POST:#"yourURL" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:[operation responseData] options:0 error:&error];
NSLog(#"JSON: %#", json);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
In case if everything else doesn't work, try to pass parameters in url:
NSString *URL=[[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login?userName=aps#test.com&deviceCode=bhj234&pwd=1234"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSLog(#"post:%#",URL);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Once it worked for me, however this of course doesn't answer what is the problem with your code.
I found the answer for my question.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"aps#test.com" forKey:#"userName"];
[dict setValue:#"vikkj107" forKey:#"deviceCode"];
[dict setValue:#"1234" forKey:#"pwd"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONReadingMutableLeaves error:nil];
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv/Register"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *resultStr=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
I have used JSON Serialization to get json response, here i'mn getting all fine, but when i need to post some values as key value pair with the URL. I have done like this, but didn't get the result.
NSArray *objects = [NSArray arrayWithObjects:#"uname", #"pwd", #"req",nil];
NSArray *keys = [NSArray arrayWithObjects:#"ann", #"ann", #"login", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
// NSLog(#"Success");
}
}
NSURL * url =[NSURL URLWithString:#"URL_address_VALUE/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[result length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:result];
NSURLResponse *res = nil;
NSError *error = nil;
NSData *ans = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
if (error == nil) {
NSString *strData = [[NSString alloc]initWithData:ans encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
I don't know what goes wrong here... Please dudes help me..
There are multiple Errors in your Code, Use my Code as a Reference and compare it to yours and you'll get the Errors done by you.
The Below code is working correctly from the Point of View of Objective-C. There are some Errors regarding your URL or Service Side.
Working Code :
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"ann",#"uname",#"ann",#"pwd",#"login",#"req", nil];
NSLog(#"dict :: %#",dict);
NSError *error2;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error2];
NSString *post = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLength :: %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://exemplarr-itsolutions.com/dbook/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error3;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error3];
NSString *str = [[NSString alloc] initWithData:POSTReply encoding:NSUTF8StringEncoding];
NSLog(#"str :: %#",str);