My question is:
How can I create the same request as below using ASIFormDataRequestand second as I think I need to parse JSON from response.
http://exampledomain.com/mobile_api/register/?client=iphone&info=A=iPhone/OS=5.1/C=UA&time=1342780143&udid=8b6f0cc104d137ae2e1730235f5664094b831122&version=1.0&secure=5444d72741bad93b916577d9297fa
Now I try to use code like this
NSString *strURL = #"http://test2.mafia.ua/mobile_api/register/";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setPostValue:#"iphone" forKey:#"client"];
[request setPostValue:#"A=iPhone/OS=5.1/C=UA" forKey:#"info"];
[request setPostValue:#"1342780143" forKey:#"time"];
[request setPostValue:#"8b6f0cc104d137ae2e1730235f5664094b831122" forKey:#"udid"];
[request setPostValue:#"1.0" forKey:#"version"];
[request setPostValue:#"5444d72741bad93b916577d9297fa" forKey:#"secure"];
[request startAsynchronous];
is this correct?
I implement delegate method also
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"Response %d ==> %#", request.responseStatusCode, [request responseString]);
}
- (void)requestFailed:(ASIHTTPRequest *)request {
}
In response I get this (I think this is JSON) if I use some browser.
{"status": "ok", "secret": "b82b7771f600772c2c5af903b117b5e", "client": "200004", "expires": "1345372850"}
You're passing your data in POST fields (That's what setPostValue: does.)
You should be including them in your URL instead; try searching around for an easy way of building query parameters in a URL or just use something like stringWithFormat: and appropriate escaping.
Related
I am currently building an app in Xcode using Objective C and I need to post two text variables and an image. As of right now, I can only post the two text variables but I would like to send an image from my UIImageView to the server by using the FILES variable from the HTTP POST Request.
Here is the working code for my POST Request:
- (IBAction)posttoserver:(id)sender {
NSString *post = [NSString stringWithFormat:#"process=writepost&auth_token=%#&app_id=0&posttextarea=%#&url=%#", authkey, encodedmessage, encodedlink];
NSData *data = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"my-server.com"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connection!");
}
else {
NSLog(#"No Connection");
}
[_posttext resignFirstResponder];
[_postlink resignFirstResponder];
}
Continued:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Post Response: %#", response);
if ([response isEqualToString:#"success"]) {
// NSLog Success
}
else {
// Something is wrong
}
}
As you can see, I am posting the user editable text as well as a link for the post. Also, you might notice that I am attaching "process=writepost&auth_token=%#&app_id=0" and those are just needed for the server to recognize who is posting and what process is being sent to the specific URL.
Now, I would like to attach an image to the POST request by adding an image from the UIImageView. How would I attach it into the FILES variable for the POST request?
Any help would be gladly appreciated.
Thanks in advance,
Kyle
Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.
I've been reading over code samples and posts for days but I haven't found a definitive way to post JSON data from my Core Data objects to a RESTful web service. There's a TON of documentation about pulling the JSON from a web service but not so much about sending stuff back. Can anyone point me to a good example or post some code on how to do it? I'm using Core Data and I have the object I want to send back mapped to a Dictionary but I'm missing the code to send it to the service.
EDIT:
I ended up with the code below which looks right and runs without errors, but I get 0 bytes of data returned and my webservice doesn't seem to be receiving the request. The JSON data looks good, the URL is correct, and I can hit the webservice and get JSON data back from it. The NSURLConnection delegate methods also fire as expected.
Is there anything I'm missing below?
- (void)SubmitSystems
{
NSFetchRequest * allSystems = [[NSFetchRequest alloc] init];
[allSystems setEntity:[NSEntityDescription entityForName:#"System" inManagedObjectContext:self.managedObjectContext]];
NSError * error = nil;
NSArray * systems = [self.managedObjectContext executeFetchRequest:allSystems error:&error];
//error handling goes here
//for (NSManagedObject * system in systems) {
NSManagedObject *system = systems[2];
NSString *entityString = #"System";
NSString * serverString = [NSString stringWithFormat:#"%#%#", kWebServiceAddress, entityString];
NSURL *url = [NSURL URLWithString:serverString];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:[self jsonSystemDictionary:(System *)system] options:kNilOptions error:&error];
//NSLog([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); //debug only
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30.f];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//}
}
You're going to need to NSMutableURLRequest. Using this, you can use setHTTPMethod and pass it the #"POST" string, and then use the attributes of your NSManagedObject to populate the URL, HTTPBody and/or HTTPHeader as needed.
I'm using ASIHttpRequest to send data back and forth to the server in my IOS game.
I'm wondering if someone can see the url being send to the server, someway?
... If that's the case, cheating is possible.
thanks in advance
The request looks like this:
NSURL *url = [NSURL URLWithString: #"http://xx.xxx.xx.x/development/"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: url];
__weak ASIHTTPRequest *request_b = request;
[request setDelegate: self];
[request setQueue: [[DatabaseHelper sharedInstance] networkQue]];
[request setShouldContinueWhenAppEntersBackground: NO];
[request addRequestHeader:#"Content-Type" value:#"text/html; charset=utf-8;"];
[request setDefaultResponseEncoding:NSUTF8StringEncoding];
[request setTimeOutSeconds: 20.0f];
[request setCachePolicy: ASIDoNotWriteToCacheCachePolicy | ASIDoNotReadFromCacheCachePolicy];
[request setPostValue:#"aSecretString" forKey:#"secret"];
[request setPostValue: #"updateUser" forKey:#"apiToRun"];
[request setPostValue: #"4" forKey:#"userId"];
url:
http://xx.xxx.xx.x/development/secret=aSecretString&apiToRun=updateUser&userId=4
With a GET request, data is sent as part of the URL and is easy to intercept with HTTP monitoring. If you use POST, this information will not be visible in the URL.
Hi I am using ASIHTTPRequest POST for adding time entry on basecamp for logged in user.
But
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
method of ASIHTTPRequest is getting called and in
- (void)requestFailed:(ASIHTTPRequest *)request
I am getting error as access denied.
I also need to send aunthentication token to basecamp URl please help me how to do this.
NSString *postData=[NSString stringWithFormat: #"<time-entry>\
<person-id> 898989 </person-id>\
<date>2011-04-07</date>\
<hours>2:00</hours>\
<description>test</description>\
</time-entry>"];
NSURL *url = [NSURL URLWithString:#"https://test.basecamphq.com/projects/4644/time_entries.xml"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request appendPostData:[postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request addRequestHeader:#"Accept" value:#"application/xml"];
[request addRequestHeader:#"Content-Type" value:#"application/xml"];
[request authenticationNeeded];
[request setValidatesSecureCertificate:NO];
[request startAsynchronous];
This is my code. Please help.
Assuming this is the right API doc:
http://developer.37signals.com/basecamp/
Then basecamp using HTTP basic authentication, meaning you need to do this:
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
[request setUsername:yourApiToken];
[request setPassword:#"X"];
Putting your API token where it says 'yourApiToken'.