I'm using a service with REST API, which provides me an authentication token as the response for the sign in POST request.
Now for authentication on every request i need to send that token with the request.
How to use this token with every request i send to server ???
I'm not totally sure what you need from your question, but here is a guess.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://rest.u.rl/do/this"];
NSString *header = [NSString stringWithFormat:#"%#",token]; //format as needed
[request setValue:header forHTTPHeaderField:#"TokenFieldName"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod: #"POST"];
And to do this for every other one, do a if (i % 2 == 0) or something to that effect.
Related
I'm developing iPhone app and manually constructing POST requests. Currently, need to compress JSON data before sending it, so looking how to tell a server the content is compressed. Setting content type header to gzip might be not acceptable because server expects JSON data. I'm looking for transparent solution, something like just to add some header telling JSON data is compressed into gzip.
I know, the standard way is to tell the server that the client accepts encoding, but you need to make GET request with accept encoding header first. In my case, I want to post the data already encoded.
Include a Obj-C gzip wrapper, for example NSData+GZip, and use it to encode the body of your NSURLRequest. Also remember to set the Content-Encoding accordingly, so the webserver will know how to treat your request.
NSData *requestBodyData = [yourData gzippedData];
NSString *postLength = [NSString stringWithFormat:#"%d", requestBodyData.length];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"gzip" forHTTPHeaderField:#"Content-Encoding"];
[request setHTTPBody:requestBodyData];
Implmenting some general Method such as follows and setting appropriate Header might help you.
// constructing connection request for url with no local and remote cache data and timeout seconds
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:callingWebAddress]];// cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:timoutseconds];
[request setHTTPMethod:#"POST"];
NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];
[headerDictionary setObject:#"application/json, text/javascript" forKey:#"Accept"];
[headerDictionary setObject:#"application/json" forKey:#"Content-Type"];
//Edit as #centurion suggested
[headerDictionary setObject:#"Content-Encoding" forKey:#"gzip"];
[headerDictionary setObject:[NSString stringWithFormat:#"POST /Json/%# HTTP/1.1",method] forKey:#"Request"];
[request setAllHTTPHeaderFields:headerDictionary];
// allocation mem for body data
self.bodyData = [NSMutableData data];
[self appendPostString:[parameter JSONFragment]];
// set post body to request
[request setHTTPBody:bodyData];
NSLog(#"sending data %#",[[[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding]autorelease]);
// create new connection for the request
// schedule this connection to respond to the current run loop with common loop mode.
NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//[aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
self.requestConnenction = aConnection;
[aConnection release];
I am trying to set up a cache, however the method I am using 'as below' is not being accessed by the thread.
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
I am initializing the connection like this, and connectionDidFinishLoading is accessed so I am not sure what I am missing.
- (IBAction)searchRequest:(NSData *)postBodyData
{
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:#"https://127.0.0.1:88"];
NSURL *url = [NSURL URLWithString:databaseURL];
NSString *postLength = [NSString stringWithFormat:#"%d", [postBodyData length]];
//SynchronousRequest to grab the data, also setting up the cachePolicy
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0]; //if request dose not finish happen within 60 second timeout.
// NSInputStream *fileStream = [NSInputStream inputStreamWithData:postBodyData];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/octet-stream" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:postBodyData];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [NSMutableData data];
} else {
// Inform the user that the connection failed from the connection:didFailWithError method
}
}
any help would be appreciated.
connection:willCacheResponse: is only called in cases when the response will be cached. POST requests are not cacheable in most cases. (More details: Is it possible to cache POST methods in HTTP?)
You should probably look at something like MKNetworkKit which handles a lot of this kind of caching, particularly for REST protocols.
You can also look at Drop-in offline caching for UIWebView. You'd have to modify it significantly, but NSURLProtocol can be used to solve this kind of problem. AFCache is currently working to integrate this approach, and is another toolkit to consider. (Read through the comments in the blog post for more background on the issues.)
I have the following requirement to call a service using an ASIHTTPRequest with a POST method call. When I execute the request I get the following error:
errorError Domain=ASIHTTPRequestErrorDomain Code=5 "Unable to create request (bad url?)" UserInfo=0x790b490 {NSLocalizedDescription=Unable to create request (bad url?)}
And heres my code:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:SampleURL]];
[request addPostValue:#"emailid" forKey:username.text];
[request addPostValue:#"password" forKey:password.text];
[request addPostValue:#"first_name" forKey:first_name];
[request addPostValue:#"last_name" forKey:last_name];
[request addPostValue:#"option" forKey:#"userSignup"];
request.delegate = self;
[request startSynchronous];
Can anyone help me on this?
NSString *safestring=[strUrl stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url= [NSURL URLWithString:safestring];
[request addPostValue:#"emailid" forKey:username.text];
Shouldn't that be in the opposite order: [request addPostValue:username.text forKey:#"emailid"];
Same for the rest...
It looks like that 'sampleURL' has some issue. What is the data type of sampleUL? it should be NSURL.
Also what is in sampleURL when this piece of code is executed.
I am just trying to fetch the Preapproval Key from PayPal server right from my iPhone App instead of setting up a Separate server for that. (For Testing Purpose). Can this be achieved?
I have used the following code to do that:
NSString *url = #"requestEnvelope.errorLanguage=en_US&cancelUrl=http://www.bytelyte.com/PayPal_X_NVP_tester.php?cmd=test¤cyCode=USD&endingDate=27.05.11 &maxAmountPerPayment=5&maxNumberOfPayments=2&maxTotalAmountOfAllPayments=5&pinType=NOT_REQUIRED&returnUrl=http://www.bytelyte.com/PayPal_X_NVP_tester.php?cmd=test&startingDate=27.01.11&senderEmail=krish_1297240918_per#gmail.com//www.bytelyte.com/PayPal_X_NVP_tester.php?cmd=test&startingDate=27.01.11&senderEmail=krish_1297240918_per#gmail.com";
NSData *postData = [url dataUsingEncoding:NSASCIIStringEncodinallowLossyConversion:YES];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setTimeoutInterval:1.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"XXYYZZZZ" forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
[request setValue:#"XXYYZZZZ" forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[request setValue:#"XXYYZZZZ" forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
[request setValue:#"NV" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[request setValue:#"NV" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[request setValue:#"127.0.0.1" forHTTPHeaderField:#"X-PAYPAL-DEVICE-IPADDRESS"];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"utf-8" forHTTPHeaderField:#"charset"];
The Response I have got is the following:
responseEnvelope.timestamp=2011-02-09T05%3A02%3A38.859-08%3A00&responseEnvelope.ack=Failure&responseEnvelope.correlationId=981f044262212&responseEnvelope.build=1655692&error(0).errorId=560029&error(0).domain=PLATFORM&error(0).severity=Error&error(0).category=Application&error(0).message=The+required+X-PAYPAL-APPLICATION-ID+header+is+missing+from+the+HTTP+request&error(0).parameter(0)=X-PAYPAL-APPLICATION-ID
Am I missing something or this is entirely not possible?
#Krishnan, seems you are missing a HTTP header called X-PAYPAL-APPLICATION-ID.
I am currently looking into GAE (Python) and I'm trying to send POST requests from an iPhone application.
Sending with GET method works fine, but it just fails when I use POST method.
Here's the server side:
class echoHandler(webapp.RequestHandler):
def get(self):
password = self.request.get("password")
if password == "ping":
self.response.out.write("pong")
else:
self.response.out.write("erreur de password")
def post(self):
password = self.request.get("password")
if password == "ping":
self.response.out.write("pong")
else:
self.response.out.write("erreur de password")
and on the client side:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://myapp.appspot.com/echo"]];
NSMutableURLRequest *maRequete = [NSMutableURLRequest requestWithURL:url];
[maRequete setHTTPMethod:#"POST"];
NSString *essaiMdp = #"password=ping";
[maRequete setHTTPBody:[essaiMdp dataUsingEncoding:NSUTF8StringEncoding]];
//[maRequete setValue:[NSString stringWithFormat:#"%d",[essaiMdp length]] forHTTPHeaderField:#"Content-Length"];
//[maRequete setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
//[maRequete setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLResponse *reponse;
NSError *erreur;
NSData *donneesPOST = [NSURLConnection sendSynchronousRequest:maRequete returningResponse:&reponse error:&erreur];
if (donneesPOST) {
NSString *strResultat = [[NSString alloc] initWithData:donneesPOST encoding:NSUTF8StringEncoding];
NSLog(#"reponse recue !");
NSLog(strResultat);
resultat.text = strResultat;
}
else {
if (erreur) {
NSLog(#"erreur lors de la requete HTTP:%#", url);
NSLog(#"erreur: %#", [erreur localizedDescription]);
}
}
What's weird is that everything works in localhost, but when I deploy the app on the internet, POST method stopped working.
Any idea ? Thx !
Is there a possibility that your server is set up to redirect requests that don't end in a slash to one that does? In other words, maybe http://myapp.appspot.com/echo is redirecting to http://myapp.appspot.com/echo/, and a redirect is always a GET.
If you are sending a POST request to Google App Engine, change the URL to 'https' "http://myapp.appspot.com/echo" to "https://myapp.appspot.com/echo".
From what i have experienced, sending a "non-https" url to Google App Engine causes a redirect.