How to convert NSURLConnection to AFNetworking? - ios

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.

Related

Json Code is not working

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

AFNetworking2 send parameter as query string in POST request?

I need to send query string in URL as well as JSON in body while making POST request.To send query string in url i override HTTPMethodsEncodingParametersInURI property as suggested in this thread on SO like
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:fullUrl]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", #"PUT", #"DELETE"]];
[manager POST:fullUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
but it seems doing this add my JSON data into URL as well, hence my request is not executed on server.But i need to send only 'command' parameter into url and some JSON data into request body.
my fullUrl string is looks like http://some_ip_address/config?command=some_command and param is NSDictionary object.
Note that there is a parameter in fullUrl i.e. command and i also send a NSDictionary object as param in
[manager POST:fullUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Edit2: I also tried with NSURLSession
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://my_server_ip/config?command=plugs"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
but get status code: 400 in NSURLResponse.
Edit3: someone suggested to subclass AFHTTPRequestSerializer class in this SO thread so i tried with
#implementation CustomAFHTTPRequestSerializer
-(id)init
{
self = [super init];
return self;
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
error:(NSError *__autoreleasing *)error
{
NSString* encodedUrl = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error1;
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error1];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
return request;
}
#end
And assign it as requestSerializer of operationManager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [[CustomAFHTTPRequestSerializer alloc] init];
But still get Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
Please help me guys, Any help would be highly appreciated.

post json array to server in iOS?

i am trying to send json array data to server but it show the result is failed.
so plaese correct me where i did wrong.Here is code what i am using in this:
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [NSString stringWithFormat:#"%#",jsonString];
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:#"http://anaadit.net/caffe/newapp/AddGroupContact.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn==nil) {
NSLog(#"Connection could not be made");
} else {
responseData = [NSMutableData new];
NSLog(#"%#",responseData);
}
and nsurl connection delegate methods calling but the response is showing is nil .
so please check and correct me .Thanks in advance.
Use AFNetworking frame work instead, easy to use and implement.
https://github.com/AFNetworking/AFNetworking
POST request in AFNetworking -
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
manager.requestSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://anaadit.net/caffe/newapp/AddGroupContact.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
To set ant http header field you can use,
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Please contact your webservice developer, he/she may have had some issue
Your question has been answered here: How to send POST and GET request?
Although judging from your comment, the issue isn't with the actual request but rather with the server. You wouldn't have gotten a response if your request code was faulty. You should check that the parameters are corresponding with what the server needs.
You can also check the status code of the request like so:
[(NSHTTPURLResponse*)response statusCode]

POST request with JSON body AFNetworking 2.0

Is there anyway to send a POST request with a JSON body using AFNetworking ~> 2.0?
I have tried using:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager POST:<url> parameters: #{#"data":#"value"} success: <block> failure: <block>'
but it doesn't work. Any help is greatly appreciated.
Thanks
You can add your JSON body in NSMutableURLRequest not direct in parameters:. See my sample code :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set post method
[request setHTTPMethod:#"POST"];
// Set header to accept JSON request
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Your params
NSDictionary *params = #{#"data":#"value"};
// Change your 'params' dictionary to JSON string to set it into HTTP
// body. Dictionary type will be not understanding by request.
NSString *jsonString = [self getJSONStringWithDictionary:params];
// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Hope this will help you. Happy coding! :)
If someone looking for AFNetworking 3.0, here is code
NSError *writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json; encoding=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#", error);
NSLog(#"Response: %#",response);
NSLog(#"Response Object: %#",responseObject);
}
}] resume];

Format for POST Request in iOS

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

Resources