I wanted to post a string data to API, I try to send it to server by using the below code. I've check api there by using the postman, it did not pass in the string data into the server. I do not know what is the problem and need help on this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:reqURLStr]];
[request setHTTPMethod:#"POST"];
**//Pass The String to server**
NSString *userUpdate =[NSString stringWithFormat:#"service_type=%#&ParcelSize=%#&ReceiverName=%#&MobileNumber=%#&Email=%#&DropOffHub=%#&PickupHub=%#" ,serviceType,pSize,rName,rMobile,rEmail,dropHubID,pickHubID];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[data makeRestAPICall:reqURLStr] forHTTPHeaderField:#"Authorization"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"fail to connect");
}
return resSrt;
Simple answer
-(void)postJsonDataToServer{
NSDictionary *parameters = #{
#"service_type": serviceType,
#"ParcelSize": pSize,
#"ReceiverName": rName,
#"MobileNumber": rMobile,
#"Email" : rEmail,
#"DropOffHub" : dropHubID,
#"PickupHub" : pickHubID
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http:/api/order/add"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil)
{
NSError *parseError = nil;
//If the response is in dictionary format
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
//OR
//If the response is in array format
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The res is - %#",res);
}
else
NSLog(#"Data returned the parameter is nil here");
}];
[dataTask resume];
}
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 am trying to hit a web service . All works good. But if the server is not working then my app crashes .
How to handle NO SERVER RESPONSE .
Please help
Here is my code for hitting web service.
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"req=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",getCommunity]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil) {
NSDictionary *jsonRecieveDict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonArray =======%#",jsonRecieveDict);
}
if (error)
{
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Servor not responding" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[errorAlert show];
}
** ERROR IS BECAUSE OF INVALID STATUS CODE FROM SERVER **
if (error != nil) {
// Something went wrong...
NSLog(#"Servor not responding %#",error.description);
return;
}
if ([response statusCode] >= 300) {
NSLog(#"Servor not responding, status code: %ld", (long)[response statusCode]);
return;
}
First condition should be error checking,Second if response comes check the status code then only perform the remaining operation
Also change NSURLResponse *response; to NSHTTPURLResponse *response
OR diff Implementation
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
if([NSJSONSerialization isValidJSONObject:get]){
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"your url"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session=[NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(response){
NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(#"Echo %#",resp);
}
else{
NSLog(#"Timeout");
}
}];
[task resume];
}
I am trying to fetch json data from local host. I have done this so many times. But this time it is not fetching data.
Json data
{
"swimming_pool":"0",
"security":"0",
"lift":"0",
"gym":"0",
"reserved_parking":"0",
"visitor_parking":"0",
"power_backup":"0",
"servant_room":"0",
"tennis_court":"0",
"rainwater_harvesting":"0",
"waste_management":"0",
"club_house":"0",
"desc":"Dkkd",
"city":"City",
"pincode":"Pin Co",
"locality":"locality",
"no_of_beds":"1",
"no_of_baths":"4"
}
Client side code
{
NSString *selectQuery=[NSString stringWithFormat:#"http://localhost/FilterQuery.php?swimming_pool=%li&&security=%li&&lift=%li&&gym=%li&&visitor_parking=%li&&power_backup=%li&&servant_room=%li&&rainwater_harvesting=%li&&waste_management=%li&&clubhouse=%li&&Posdesc=%#&&no_of_baths=%li&&no_of_beds=%li&&pincode=%li&&locality=%#&&protypedesc=%#",(long)swimpoolb,(long)securityb,(long)liftb,(long)gymb,(long)visparkingb,(long)pbu,(long)servantroom,(long)rainwaterh,(long)wastemanagement,(long)clubHouse,possesion,(long)bathrooms,(long)bedrooms,(long)zipcode,locality,propertyType];
NSString *newInsrStr = [selectQuery stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataaa=[NSData dataWithContentsOfURL:[NSURL URLWithString:newInsrStr]];
NSString *rr=[[NSString alloc]initWithData:dataaa encoding:NSUTF8StringEncoding];
NSLog(#"%#",rr);
jsondataa=[NSJSONSerialization JSONObjectWithData:dataaa options:0 error:nil];
//jsondataa is dictionary
swimmingPool=#"";
swimmingPool=[jsondataa objectForKey:#"swimming_pool"];
security=#"";
security=[jsondataa objectForKey:#"security"];
lift=#"";
lift=[jsondataa objectForKey:#"lift"];
gym=#"";
gym=[jsondataa objectForKey:#"gym"];
reserved_parking=#"";
reserved_parking=[jsondataa objectForKey:#"reserved_parking"];
visitor_parking=#"";
visitor_parking=[jsondataa objectForKey:#"visitor_parking"];
power_backUp=#"";
power_backUp=[jsondataa objectForKey:#"power_backup"];
NSLog(#"%#,%#,%#,%#,%#,%#,%#",swimmingPool,security,lift,gym,reserved_parking,visitor_parking,power_backUp);
}
Output:
2015-06-29 15:20:51.874 NexGV1[1684:60b] Notice:
Undefined variable: tennis_court in
/Applications/XAMPP/xamppfiles/htdocs/FilterQuery.php on line
21
{"swimming_pool":"0","security":"0","lift":"0","gym":"0","reserved_parking":"0","visitor_parking":"0","power_backup":"0","servant_room":"0","tennis_court":"0","rainwater_harvesting":"0","waste_management":"0","club_house":"0","desc":"Dkkd","city":"City","pincode":"Pin
Co","locality":"locality","no_of_beds":"1","no_of_baths":"4"}
2015-06-29 15:20:51.875 NexGV1[1684:60b]
(null),(null),(null),(null),(null),(null),(null)
It is showing null value. Why?
This is suppose to be a comment but it's too long for a comment..
So, your approach is json request via url, it is not the ideal for something like this it is confusing and hard to read..
I'm so lazy checking that very long url, so i'll just introduce you to this kind of approach..
NSString *selectQuery=[NSString stringWithFormat:#"http://localhost/FilterQuery.php?swimming_pool=%li&&security=%li&&lift=%li&&gym=%li&&visitor_parking=%li&&power_backup=%li&&servant_room=%li&&rainwater_harvesting=%li&&waste_management=%li&&clubhouse=%li&&Posdesc=%#&&no_of_baths=%li&&no_of_beds=%li&&pincode=%li&&locality=%#&&protypedesc=%#",(long)swimpoolb,(long)securityb,(long)liftb,(long)gymb,(long)visparkingb,(long)pbu,(long)servantroom,(long)rainwaterh,(long)wastemanagement,(long)clubHouse,possesion,(long)bathrooms,(long)bedrooms,(long)zipcode,locality,propertyType];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:selectQuery]];
You can convert that url to request then use the NSURLConnection below..
__block NSMutableData *fragmentData = [NSMutableData data];
__block id serializedResponse;
[[NSOperationQueue mainQueue] cancelAllOperations];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[fragmentData appendData:data];
if ([data length] == 0 && error == nil)
{
NSLog(#"No response from server");
}
else if (error != nil && error.code == NSURLErrorTimedOut)
{
NSLog(#"Request time out");
}
else if (error != nil)
{
NSLog(#"Unexpected error occur: %#", error.localizedDescription);
}
else if ([data length] > 0 && error == nil)
{
if ([fragmentData length] == [response expectedContentLength])
{
NSLog(#"Received %f of data from server.", (CGFloat)[response expectedContentLength]);
serializedResponse = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSLog(#"%#", serializedResponse);
// or
NSLog(#"%#", [[NSString alloc] initWithData:fragmentData encoding:NSUTF8StringEncoding]);
}
}
}];
And also if you like the easy way to make a request using the NSURLConnection above.
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: JSONData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:#"Content-Length"];
return request;
}
and using it like:
NSDictionary *jsonDictionary = #{
#"swimming_pool": [NSNumber numberWithLong:(long)swimpoolb],
#"security" : [NSNumber numberWithLong:(long)securityb],
.. and so on
};
NSURLRequest *request = [ImplementationClass convertToRequest:YourServerURL withDictionary: jsonDictionary];
and in the server it should be:
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$json_decoded = json_decode($jsonInput,true);
$json_decoded['swimming_pool'];
$json_decoded['security'];
Hope this is informative and helpful...
my code here...
not receive all html data....so plz reply me on it:sanandiyavipul#gmail.com
NSString *get_value_key=[NSString stringWithFormat:#"personen=%#&eigenaar=%#&soortwoning=%#&beveiliging=%#&soortdak=%#",[filter_ary4 objectAtIndex:[pickerView4 selectedRowInComponent:0]],[filter_ary7 objectAtIndex:[pickerView7 selectedRowInComponent:0]],[filter_ary8 objectAtIndex:[pickerView8 selectedRowInComponent:0]],[filter_ary9 objectAtIndex:[pickerView9 selectedRowInComponent:0]],[filter_ary10 objectAtIndex:[pickerView10 selectedRowInComponent:0]]];
NSData *postData = [get_value_key dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://media.komparu.com/inboedelverzekering/10045724/5193"]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/html; charset=UTF-8" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody:postData];
// NSError *requestError;
NSURLResponse *urlResponse =nil;
response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[response1 bytes] length:[response1 length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
If you want the response it is in the variable: urlResponse.
If you want the html status code cast the response to NSHTTPURLResponse and access the statusCode property.
Or just create NSHTTPURLResponse instead of NSURLResponse and access directly.
NSError *error;
NSHTTPURLResponse *urlResponse;
response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSInteger statusCode = urlResponse.statusCode;
NSLog(#"statusCode: %i", statusCode);
if (response1) {
// process data
}
else {
// Log the response and error description
NSLog(#"urlResponse: %#", urlResponse);
NSLog(#"error: %#", error);
}