I've search and try many different solutions but without luck.
I am trying to make a JSON Request to my server, it works for sure because I've tested it in PHP (simple call, it receives string name and string password and check into the database if the user is correct). The request should receive back a JSON with property "success" only (which could be "true" or "false").
Here is my code:
- (void)logonService:(NSString *) name widthArg2:(NSString *) password {
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://46.51.169.145/ios/index.php/user/login/"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
//setting json fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//prepare output data
NSString *in1;
NSDictionary *outputData = [NSDictionary dictionaryWithObjectsAndKeys:in1, #"success", nil];
NSError *error = nil;
NSData *jsonOutputData = [NSJSONSerialization dataWithJSONObject:outputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonOutputString = [[NSString alloc] initWithData:jsonOutputData encoding:NSUTF8StringEncoding];
//set json string to body data
NSData *requestInputBodyData = [jsonOutputString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestInputBodyData];
//prepare input data
NSString *input = [NSString stringWithFormat:#"&name=%#&password=%#",name,password];
//Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *inputData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//calculate length of post data
NSString *inputLength = [NSString stringWithFormat:#"%d",[inputData length]];
//Set HTTP header field with length of the post data.
[request setValue:inputLength forHTTPHeaderField:#"Content-Length"];
//encode type
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
//add it to http body
[request setHTTPBody:inputData];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
NSLog(#"Connection Successful");
}else{
NSLog(#"Connection could not be made");
}
}
The delegate DidReceiveData fires correctly but the result is always NIL:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"RESULT1: %#", jsonResponseData);
[_responseData appendData:data];
}
Thank you, hope someone can help me!
thanks a lot for the comments, I finally fix it, and after that I decided to starting using a JSON library --> https://github.com/stig/json-framework/
This is how I finally have the code:
//prepare connection
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#user.php", _urlServer]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:#"login" forKey:#"action"];
[data setObject:username forKey:#"username"];
[data setObject:password forKey:#"password"];
//start connection
// Create the request, if there is a connection going on just cancel it.
[_connection cancel];
//initialize new mutable data
NSMutableData *receivedData = [[NSMutableData alloc] init];
_receivedData = receivedData;
//initialize the url which will be fetched
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
//initialize a post data
NSString *dataString = [[NSString alloc] init];
for(id key in data) {
id value = [data objectForKey:key];
//keys string
NSString *newData = [NSString stringWithFormat:#"&%#=%#", key, value];
dataString = [dataString stringByAppendingString: newData];
}
//set request content type we MUST set this value.
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//set post data of request
[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//NSLog(#"Sending request with parameters: %#", dataString);
//begin the connection
[_connection start];
And its working like a charm. Next step is to authenticate somehow, right now connection is open to the world.
Related
I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
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/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method
I am stuck with an issue in simple request response in iOS, I am getting blank response in request a url with one post parameter, where the url as it is perfectly working in android and webbrowser
Friends in detail, I have to call
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
it is working before, but from last few days it is not working, if I check NSError it is showing me The network connection was lost.
and one more thing noticeable here is same server code is on different url and it is working fine, and that url you can test as below
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
Here is the dropbox link for testing ios source code and also the folder contains Web services test.htm file to test that same url with same post parameter working in browser but not in ios device.
Testing code:
https://dl.dropboxusercontent.com/s/lqrl5b95j2s54mm/Testing.zip?token_hash=AAFgoNfUpQ4FkeswnPdGiMVzdMtSM6js9KySJm_OH6lZXQ&dl=1
thank you
So I could not get the form per se to work but was able to recraft it to work. Note a few things:
you should convert to ARC!
you need a strong reference to the connection so you can release it later on (and not in a delegate method!)
you need the delegate connectionSucceeded method (to record response whatever!)
CODE:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *requesturl = lblURL.text;
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"content-type"];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *str = [NSString stringWithFormat:#"key=%#", [self URLencodedString:#"Abcd1234"]];
NSLog(#"BODY: %#", str);
NSData *body = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%u", [body length]] forHTTPHeaderField:#"Content-Length"];
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
self.activeDownload = [NSMutableData data];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
assert([response isKindOfClass:[NSHTTPURLResponse class]]);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"GOT %d", [httpResponse statusCode]);
}
- (NSString *)URLencodedString:(NSString *)s
{
CFStringRef str = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)s, NULL, (CFStringRef)#"!*'();:#&;=+$,/?%#[]", kCFStringEncodingUTF8);
NSString *newString = [(NSString *)str stringByReplacingOccurrencesOfString:#" " withString:#"+"];
if(str) CFRelease(str);
return newString;
}
EDIT: Modified Code that still didn't work:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *boundary = #"1010101010"; // DFH no need for the leading '--'
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableDictionary *postVariables = [[NSMutableDictionary alloc] init];
[postVariables setValue:#"Abcd1234" forKey:#"key"];
NSString *requesturl = lblURL.text;
NSMutableString *myStr = [[NSMutableString alloc] init];
NSString *str;
// DFH - strategy is to have each line append its own terminating newline/return
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH initial boundary
[myStr appendString:str];
NSArray *formKeys = [postVariables allKeys];
for (int i = 0; i < [formKeys count]; i++) {
str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n%#\r\n",[formKeys objectAtIndex:i],[postVariables valueForKey:[formKeys objectAtIndex:i]]];
[myStr appendString:str];
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH mid or terminating boundary
[myStr appendString:str];
}
NSLog(#"BODY: %#", myStr);
NSData *body = [myStr dataUsingEncoding:NSUTF8StringEncoding];
requesturl = [self encodeStringForURL:requesturl];
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
self.activeDownload = [NSMutableData data];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"]; // DFH you add addValue, I always use setValue
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
NSLog(#"ContentType \"%#\"", contentType);
if(body)
{
[request setHTTPBody:body];
}
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
I have used ASIHTTP Library and my problem is solved
I am using web service for my iOS app.
I know how to send http post request via URL (not http Body) and get response using NSURLConnection Delegate.
But now there is better approach which I am following for web service and passing parameters in request body. I looked for library on google and found this.
But the code is bit difficult for me and I suppose there should be function for the same, which can make this bit easier.
Is there any? the code so far is below.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:**WebService URL**]];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-type"];
NSString *jsonString = [NSString stringWithFormat:#"{\n\"username\":\"%#\",\n\"%#\":\"%#\",\n\"%#\":\"%#\",\n\"%#\":%#,\n\"%#\":%#,\n\"version\":%#,\n\"name\":\"%#\"\n}",userName, #"password",pass,#"accessToken",token,#"isOnline",#"True",#"accountType",type,#"False",name];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
jsonString in this code is the http body. I want to pass parameters in request body.
Now, after executing this code i get null in NSData variable. whereas my web service function returns a value and also it returns if the execution was successful.
what is wrong in my code.
Thank you.
Thanks for your answers. Finally I found the exact solution which works absolutely fine.
I have used NSURLConnection delegate and I am passing parameter in HTTPBody in json. I am receiving response also in json.
But sending parameter directly as json is not permitted in httprequestbody so we need to take it in NSData and set content-type.
Note: specifying content type is very important.
-(void)sendDataToServer:(NSString*)userName :(NSString*)name{
{
NSArray *keys = [NSArray arrayWithObjects: #"name",#"accountType",#"isOnline",#"username", nil];
NSArray *objects = [NSArray arrayWithObjects:name,[NSNumber numberWithBool:false],[NSNumber numberWithBool:false],userName, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *myJSONString =[jsonDictionary JSONRepresentation];
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"myJSONString :%#", myJSONString);
NSLog(#"myJSONData :%#", myJSONData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:Your URL string]];
[request setHTTPBody:myJSONData];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
NSLog(#"connected");
receivedData=[[NSMutableData alloc]init];
} else {
NSLog(#"not connected");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response: %#",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(#"Succeeded! Received %lu data",(unsigned long)[receivedData length]);
NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"response: %#",responseString);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];
// show all values
for(id key in res) {
id value = [res objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;
NSLog(#"key: %#", keyAsString);
NSLog(#"value: %#", valueAsString);
}
}
P.S : You will need to add JSon files for serialization(json.h).
Check out this question nsurlrequest post body and this http post encode type
Generally, the body should conforms to "key=value" format
To your question, you need a "key" for your jsonString
[request setHTTPBody:[NSString stringWithFormat:#"postedJson=%#", jsonString]];
postedJson is the key through which you'll get the value of it at server side.
such as:
request["postedJson"]
the value returned would be the jsonString you construted
There is a typo in your sample code, this would explain the null result :
NSString ***jsonString** = [NSString stringWithFormat:#"{\n\"username\":\"%#\",\n\"%#\":\"%#\",\n\"%#\":\"%#\",\n\"%#\":%#,\n\"%#\":%#,\n\"version\":%#,\n\"name\":\"%#\"\n}",userName, #"password",pass,#"accessToken",token,#"isOnline",#"True",#"accountType",type,#"False",name];
[request setHTTPBody:[**xmlString** dataUsingEncoding:NSUTF8StringEncoding]];
Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
I am having an issue trying to fetch JSON page from one of our company's site that requires authentication.
- http://xyz.com - requires authentication
- I need to fetch data from http://xyz.com/jsonpage1
- In View DidLoad, I send user and pwd for login to establish session
- Then, I have a button that would request JSON.
This sequence doesn't work (meaning if the session loading code is in a different routine than the json loading code). If I have both codes in same routine like a view didLoad, then it seems to recognize my credentials and get JSON back. Strange! What am I missing? How is supposed to work? I thought establishing the session will create the cookie one time and no need to bother with it again? Am I losing the cookie somehow when I click the button?
-(void)viewDidLoad
{
[self establishSession];
}
-(void)establishSession{
//
//Login Session
//
NSURL *url = [NSURL URLWithString:#"http://xyz.com/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",#"abc",#"123"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d",[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:15];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[urlConnection start];
}
- (IBAction)getJSON:(id)sender
{
NSError *error = nil;
resultsView.text =#"";
[self establishLoginSession]; //I have to have this line here to get it to work ?????
//get JSON
NSURL *jurl = [NSURL URLWithString:#"http://xyz.com/jsonPage1"];
NSData *jdata = [NSData dataWithContentsOfURL:jurl options:NSDataReadingUncached error:&error];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:jdata //1
options:kNilOptions
error:&error];
NSString *dataString = [[NSString alloc]initWithData:jdata encoding:NSUTF8StringEncoding];
resultsView.text = dataString;
}
//Not sure if I need the cookie??
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse*) response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
if([fields valueForKey:#"Set-Cookie"])
cookie = [fields valueForKey:#"Set-Cookie"];
}
You can only make one request with a NSURLConnection object, so you should create it right before you're making the request.