NSData is returning 0 bytes - ios

I am trying to do a simple POST request. However the results seem different in POSTMAN plugin in chrome and in iOS simulator.
Here is the snapshot from POSTMAN:
As you can see, I get the JSON data in retun.
Here is my code to do the POST request:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:kPostURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *params =[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#&password=%#&switchid=%d&didflag=%#",fname,lname,email,pass,switchid,flag];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"response is %#",response);
NSLog(#"erros is %#",error);
NSMutableDictionary * innerJson = [NSJSONSerialization
JSONObjectWithData:data options:kNilOptions error:&error
];
NSLog(#"JSON data is %#",innerJson);
}];
[postDataTask resume];
And when I try to print the values in debugger, I get
JSON as null and NSData as 0 bytes. But I get the status code as 200 which is a success.
HEre is the response I get:
{ status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 0;
"Content-Type" = "text/html";
Date = "Thu, 25 Feb 2016 02:04:02 GMT";
"Keep-Alive" = "timeout=5";
Server = "Apache/2.4.12";
"X-Powered-By" = "PHP/5.5.30";
} }
Why do I get NSData as 0 bytes ?

in the request in chrome you have the parameters as URL params. in the ObjC version you are adding the params as part of the post.
instead of adding the the params as part of the body:
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
add it as part of the query:
NSURL *url = [NSURL URLWithString:[kPostURL stringByAppendingFormat:#"?%#", params]];

Related

POST method resulting status code 400 ios

I have tried many times, but i cant do a simple POST request to a remote API.. I need to post username and password to get a login authorization. Here are the code:
NSURL * url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSString *postData = #"username=emailExample#gmail.com&password=123456";
NSData * dataBody = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d",[dataBody length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:dataBody];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
I have made another version, witch uses NSDictionary and Json parsing (the API uses json)
NSDictionary * login = #{#"username":#"exampleMail#gmail",#"password":#"123456"};
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:login options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLenght = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
And here is the result of both codes:
2016-06-18 05:24:20.329 Hoffmann iOS[10317:1088208]
ERROR (null), RESPONSE <NSHTTPURLResponse: 0x796bee60>
{ URL: http://thapi.xyz/auth/login } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 70;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 18 Jun 2016 04:24:18 GMT";
Etag = "W/\"46-22Kcj8zTKrWgQ7OCr429+w\"";
Server = "nginx/1.6.2";
Vary = "Accept-Encoding";
"X-Powered-By" = undefined;
"X-Response-Time" = "5.357ms";
} } AND DATA {"name":"ParameterError","message":"Request should contain: username"}
I really appreciate all answers, and sorry for my bad english...
Perhaps the misspelling of the header variable is the issue ("Content-Lenght" is misspelled):
[request setValue:postLenght forHTTPHeaderField:#"Content-Length"];
NSURLConnection is deprecated. use nsurlsession instead Try this code....
//replace the following code with your request params
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *clientSessionId = [prefs stringForKey:#"clientSession"];
NSString *bodyString = [NSString stringWithFormat:#"[\"%#\",{\"session_token\":\"%#\",\"request\":[\"GetUnitDetails\",{}]}]",clientSessionId,clientSessionId];
//Make mutable url request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[Settings getMobileUrl]]];
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
//Change the http method as per your own choice
[request setHTTPMethod:#"POST"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *connectionError)
{
if ([data length] > 0 && connectionError == nil)
{
NSError *localError = nil;
self.parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
NSString* unitResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [unitResponse dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
}else {
NSLog(#"No response received");
}
}]resume];
You could try using a NSDictionary for the parameters. The following will send the parameters correctly to a JSON server.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *login = [[NSDictionary alloc] initWithObjectsAndKeys: #"username":#"exampleMail#gmail",#"password":#"123456",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:login options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
Hope this works Properly...:)
try also to correct "setValue:postLenght", since I guess that doesn't exist, and will probably set Content-Length to 0.

How to send request to soap webservice in ios?

hi i want to send request to the soap webservice. I tried in AFnetworking and getting internal server error 500 and now iam trying in nsurlconnection but it also showing status code 400. Please any one help me. Thank you Advance hear is My code.
NSString *soapString = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body><addBusOrder xmlns=\"http://tempuri.org/\"><UserUniqueID>ok//8FjcvEKWMeeJJZHKYA</UserUniqueID><PlatFormID>4</PlatFormID><DeviceID>E3D2FCF6-F41B-4275-BD34-FAA31307EFFE</DeviceID><RouteScheduleId>532875503</RouteScheduleId><JourneyDate>2016-03-25</JourneyDate><FromCityid>734</FromCityid><ToCityid>202</ToCityid><TyPickUpID>22860424</TyPickUpID><Contactinfo><Name>vinod</Name><Email>katragadda.vinod#gmail.com</Email><Phoneno>7842768497</Phoneno><mobile>8801720427</mobile></Contactinfo><pass><passenger><passengerName>kumar</passengerName><Age>23</Age><Fare>1072</Fare><Gender>M</Gender><Seatno>D3</Seatno></passenger></pass></addBusOrder></soap:Body></soap:Envelope></addBusOrder></soap12:Body></soap12:Envelope>"];
NSLog(#"soapString %#",soapString);
NSString *msgLength = [NSString stringWithFormat:#"%li", [soapString length]];
NSString *queryString = [NSString stringWithFormat: #"https://asprel.in/Service/AppServices.asmx/addBusOrder"];
NSURL *url = [NSURL URLWithString:queryString];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:#"application/soap+xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req addValue:#"http://tempuri.org/addBusOrder" forHTTPHeaderField:#"SOAPAction"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapString dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(#"error %#",connectionError);
}else{
NSLog(#"data %#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
[parser parse];
}];
}
Error:
status code: 500, headers {
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = private;
"Content-Length" = 322;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Thu, 24 Mar 2016 07:08:32 GMT";
Etag = "\"\"";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
You need the API Authorization
try add Authorization
// Create the request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
// New Create the connection
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sharedSession];//sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// NSURLCredential *creds = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceForSession];
NSString *authStr = [NSString stringWithFormat:#"%#:%#",username API,password API];// #"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: #"Basic %#",[authData base64EncodedStringWithOptions:0]];
// Part Important
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request addValue:#"application/soap+xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request addValue:#"http://tempuri.org/addBusOrder" forHTTPHeaderField:#"SOAPAction"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [soapString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
[parser parse];
NSLog(#"%#",responseData);
if (error) {
[self handleError: error];
}
}];
[dataTask resume];
NSLog(#"Header Request--->> %#",request.allHTTPHeaderFields);

NSURLSession POST is not working and returning 500 status code in iphone

When i am using NSURLSession while Posting through the Browser is returning the result as 200 status but when i send it through code in IOS i am getting 500 status code as below.
Response:<NSHTTPURLResponse: 0x14e754240> { URL: urlAPI } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 30;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Thu, 28 Jan 2016 12:59:10 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
Below is my code
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"HERE IS MY URL"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params =#"MY PARAMETERS";
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[dataTask resume];
This code worked previously but it is throwing error now(API code also not changed),where am i doing wrong.Help me out of this.
Try to send the parameters in NSDictionary:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#“[Your SERVER URL”];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *postData = [[NSDictionary alloc] initWithObjectsAndKeys: #“TestUservalue”, #"name",
#“TestPassvalue”, #“password”,
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject: postData options:0 error:&error];
[request setHTTPBody: postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
The problem is with the parameters that you are sending to your webserver. They must be properly encoded. I was having the same 500 status code.
I was able to fix my problem by changing my post parameters. I removed the _ from my post variables name and it worked.
NSString * params = [NSString stringWithFormat:#"q_id=%#&c_id=%#&agent=%#",self.q_id, self.c_id, agent];
// changed to
NSString * params = [NSString stringWithFormat:#"qid=%#&cid=%#&agent=%#",self.q_id, self.c_id, agent];
Also check out this link on Objective-C encoding

Objective c post request not sending the data

Good day.Im trying to send simple post data to server.This is the code how i do it.
-(void)makeRequest:(NSString*)stringParameters{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://vaenterprises.webatu.com/Authentication.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/text" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/text" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString* postData = #"tag=hello&username=yo&something=something";
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[self parseJson:data];
}];
[postDataTask resume];
}
It looks great till i echo the whole post from php side like this
echo json_encode($_POST);
and i print the result in the iOS like this
-(void)parseJson:(NSData*) data{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary* jsonObject= [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
NSLog(#"%#",myString);
}
this issue is that i get empty string..so it means that post data not being send and that is 10000 percent objective c side issue and i have no clue why its so as in this method we only got setHttpBody with the actual string which contains key and value separated by & but that data not being send as you can see.So what am i doing wrong?Please tell somebody
Http body has to be of type NSData. Try out following code
NSString* stringData = #"tag=hello&username=yo&something=something";
NSData* data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];

how to pass a dictionary using NSURLSession in post method?

I do not know how to pass values in dictionary into server using NSURLSession via POST. Please help me to solve this problem.
My dictionary contains contact information (name and phone number only), where the key is the person's name and the value is their phone number.
I have sample code using nsurl connection - how can I convert it to use NSURLSession?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://holla.com/login"]];
request.HTTPMethod = #"POST"; [request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I solve the problem by using the following method:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:#"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[postDataTask resume];

Resources