I am having trouble sending asynchronous NSURLRequests to a Ruby server. When I use the following, a connection is never made:
self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
However, when I exchange the last line with:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Everything works great. But I do need to make this connection asynchronously...
EDIT-Working Example
NSURL *url = [NSURL URLWithString:#"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:#"data"];
[request setDelegate:self];
[request startAsynchronous];
It seems RESTful services need their own third party framework in this case.
you can try following using restkit api
- (void)sendAsJSON:(NSDictionary*)dictionary {
RKClient *client = [RKClient clientWithBaseURL:#"http://restkit.org"];
// create a JSON string from your NSDictionary
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];
// send your data
if (!error)
[[RKClient sharedClient] post:#"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
}
referance:
https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON
Thanks
Nikhil
Related
I am getting "401 Unauthorized access to the endpoint". When I run the same call on POSTMAN (Chrome Extension), it works fine. Even it works fine in my Android app.
But here, I am getting the unauthorized access even if I am sending token in headers. I have no idea what is going wrong here. The response I am getting is:
{"detail":"Authentication credentials were not provided."}
Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url=[NSString stringWithFormat:#"%#",endpoint];
NSLog(#"url is %#",url);
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *token=[NSString stringWithFormat:#"token %#",TOKEN];
NSLog(#"token is %#",token);
[request addValue:token forHTTPHeaderField:#"Authorization"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];
What and where am I doing something wrong?
Edit: If I tried this way by using different class, the response is (null).
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *token=[NSString stringWithFormat:#"token %#",[[NSUserDefaults standardUserDefaults]valueForKey:D_KEY_TOKEN]];
[request setValue:token forHTTPHeaderField:#"Authorization"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSLog(#"url response is %#",urlResponse);
Edit2:
NSString *url=[NSString stringWithFormat:#"%#/",endpoint];
This is what I have done just append the slash(/)at the end of endpoint at it starts working. I want to know why there is a need to append slash at the end? All my other calls are working without slash.
Try to put a slash "/" at the end of the url.
I am developing an iOS application that connects with jira instance and i login using NSURLConnection like below -
NSString *authStr =[[NSString alloc] initWithFormat:#"%#:%#",[self.txtUsername text],[self.txtPassword text]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://hp.myDomain.com/rest/api/2/issue/createmeta?"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
and as i am using a BASIC authentication which is stateless and i wanted to know how can i logout the user now , i have tried the below code when a logout button is clicked . Can anyone please let me know if it is the right code and what is the right rest api for jira to logout an user?
-(IBAction)logout:(NSURLConnection *)conn
{
NSError *error;
NSURLResponse *response;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myDoamin.co/logout.htm"]];
[request setHTTPMethod:#"GET"];
//[request setTimeoutInterval:30.0];
[conn initWithRequest:request delegate:self];
}
For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!
It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes
So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.
I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
I'm trying to send JSON post using NSURLConnection:
NSURL *url = [NSURL URLWithString:urlStr];
NSString *jsonPostBody = [NSString stringWithFormat:#"{\"user\":""\"%#\""",\"pass\":""\"%#\""",\"listades\":\"\"}",
[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"JSNON BODY:%#", jsonPostBody);
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setTimeoutInterval:2.0];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:#"%d", [postData length]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
App execution gets freeze when it reaches connection command, despite timeout.
I'm stucked in this issue and I can not find a solution.
Many thanks
-(void) jsonRESTWebServiceMethod:(NSString*)method WithParameter:(NSMutableDictionary*)params{
self.iResponseType = JSONTYPE;
NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:method,#"name",params,#"body",nil,nil];
NSData *data = [[CJSONSerializer serializer] serializeObject:bodyDict error:nil];
NSString *strRequest = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
strRequest = [NSString stringWithFormat:#"json=%#",strRequest];
NSData *body = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString *strURL = [NSString stringWithString:WebServiceURL];
NSString* escapedUrlString = [strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
NSString *msgLength = [NSString stringWithFormat:#"%d",strRequest.length];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
if (mydata) {
[mydata release];
mydata = nil;
}
conections = [[NSURLConnection alloc] initWithRequest:request delegate:self];
mydata = [[NSMutableData alloc] init];
}
It's freezing your app because you have passed YES into startImmediately. This will freeze the app until request is finished.
You need to use something like connectionWithRequest:delegate: - this will run the request in the background and tell you when it's done.
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];