I want to create HTTP request post and get response by using simple Objective C Code method. Here below code to I can post successfully. But I didn't receive response data's. Response printing null value only. Please help me, I need to get response data's.
Here below my code
NSString *post = [NSString stringWithFormat:#"name=%#",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:#"response"];
NSLog(#"UPDATE RESPONSE : %#", respon);
You's data post is NSString *post = [NSString stringWithFormat:#"name=%#",name]; . So in this case you need set request header "Content-Type" to "application/x-www-form-urlencoded" or use following code to convert string to data and set Content-Type header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
...
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Its very simple:
//-- Convert string into URL
NSString *jsonUrlString = [NSString stringWithFormat:#"demo.com/your_server_db_name/service/link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Send request to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//-- Send username & password for url authorization
[request setValue: jsonUrlString forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"]; //-- Request method GET/POST
//-- Receive response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
Sample : https://github.com/svmrajesh/Json-Sample
Related
I am trying to send JSON data to server, but it is not go to server. I am getting nil data to print from server side but no use . Here I am using code for post data to server
NSError *error;
NSDictionary *dict=#{
#"allgroups": #{
#"groupname": #"prasad",
#"group_id":#"26",
#"user_id":#"8",
#"contacts": #[contactsArray]
}
};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *saveString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSString *myRequestString = [NSString stringWithFormat:#"%#",saveString];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat:#"http://example.php"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod: #"POST"];
//post section
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"String value is:: %#",returnString);
please help me.thanks in advance
Following function is working for me .You can use it:
-(NSMutableArray*)Post_method:(NSString*)post_string posturl:(NSString *)post_url
{
NSString *post =post_string;
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",kBaseURL,post_url]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* aStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
SBJSON *json=[[SBJSON alloc]init];
NSMutableArray *resultp=[json objectWithString:aStr];
//NSLog(#"result %# ",resultp);
return results;
}
And call this function as:
[self Post_method:[NSString stringWithFormat:#"%#",jsonString] posturl:#""];
You should directly pass your jsonData to NSMutableURLRequest like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat:#"http://example.php"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod: #"POST"];
[request setHTTPBody:jsonData];
NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
stringForKey:#"AuthToken"];
NSString* json =[NSString stringWithFormat:#"{'DeviceId':'%#','DeviceType':'iOS','UM_Identifier':'%#','AuthToken':'%#','Query':'all'}", deviceId, userEmail, AuthToken];
NSString *post =[[NSString alloc] initWithFormat:#"jinpAllCustDetails=%#",json];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [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/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
In above code :
Auth token received from last webservice response is saved in NSUserdefaults,
then used for next webservice request.
So for Eg.
Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=
But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=
ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.
Help me to fix this, thanks in advance
That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:
NSDictionary *values = #[
#"DeviceId": deviceId,
#"DeviceType": #"iOS",
#"UM_Identifier": userEmail,
#"AuthToken": authToken,
#"Query": #"all"
];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
options:0
error:&error];
NSAssert(jsonData != nil, #"Failed to create JSON data");
NSString jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
I am new to using POST, and have just written a code that takes a username and password that was entered in and sends it via POST for validation. If it is valid, it will return true, if not it will return false. I think my code works for the most part, but there must be something missing with my return data because it does not output true or false. Here is my code:
- (IBAction)btnLogIn:(id)sender;
{
//getting the username and password and putting it into a string
NSString *post =[[NSString alloc] initWithFormat:#"username= %# &password =%#",[self.lblUserName text],[self.lblPassword text]];
//output the string
NSLog(#"PostData: %#",post);
//setting the URL to post to
NSURL *url=[NSURL URLWithString:#"myurl.php"];
//converts string to data that can be used to post
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//get the length of the string
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
//formatting the URL
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/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}
I am not sure what part is missing or wrong. Everything runs fine, just returns blank when I test it out.
this is another method
//Create the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myurl.php"]];
// create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:#"username=%#&password=%#",[self.lblUserName text],[self.lblPassword text],nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
Hi Please help me how to prepare NSMutableURLRequest for below api
URL : www.XXXXXXXX.com/api.php
For Login :-
www.XXXXXXXXXXXX.com/api.php?task=login
POST Data :-
"email" => User's email
"pw" => User's Password
json response: session id on successful login
Am trying like this.
NSMutableURLRequest *request;
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.XXXXXXXX.com/api.php?task=login"]];
[request setHTTPMethod:#"POST"];
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
One reason could be that you forgot to add the "http:" scheme:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.XXXXXXXX.com/api.php?task=login]];
HERE --^
Note also that the correct way to set body data and in particular the length is
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:postData];
because the length of the UTF-8 encoded data can be different from the (Unicode) string length.
I ran into this error when I specified my base URL with a variable that accidentally contained a new line.
Try this:
NSError *error;
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithUTF8String:[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
}
[connection start];
I have successfully connected to a server, and getting correct json format String from it. Somehow 9 out of 10 times it return with something extra.. like some crap code i don't recognize. sometimes its just incomplete data. I wonder what I did wrong or what I didn't do..
does anyone has the same problem? and how can I fix it?
NSURL *siteURL = [NSURL URLWithString:tempSiteString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:siteURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30.0];
NSString *myRequestString = [NSString stringWithFormat:#"data=%#", sqlString];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[sqlString length]];
[request setHTTPMethod: #"POST" ];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
here is the code i change the received string to json
NSDictionary *tempNSDictionary = [resultString JSONValue];
if(tempNSDictionary.count==0)
{
return nil;
}
//NSLog(#"Check Point after dictionary");
NSArray *tempNSArray;
if(tempNSDictionary)
{
//NSLog(#"Check Point getArrayFromJsonString 1");
tempNSArray = [tempNSDictionary objectForKey:#"object_name"];
//NSLog(#"Check Point getArrayFromJsonString 2");
}
return tempNSArray;