HTTP POST request in iOS [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
hi i am new in ios and i didn't send any call to php till now today i have tried by the following code
-(void)sendRequest
{
NSString *vali = #"$uppl!3r$";
NSString *post = [NSString stringWithFormat:#"key1=%#",vali];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.ddemo3.enerjinet.com/webservices/ios/suppliers.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length: [webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
it should return me array of 76 records but it returns me <> can anyone please help me ? The web service is ready i need to get the array in response and show it in my table view please help me in doing this

A couple of thoughts:
You NSLog your webData, which will always show <> (as your logging it immediately after instantiated it). I'm not sure why you're logging that.
The question is whether you're seeing that <>, or the NSLog in connectionDidFinishLoading.
I ask that because you are not logging the error in connection:didFailWithError:, if it fails, you'll never know why. You really should log the error in connection:didFailWithError: so you know if it failed, and if so, why:
NSLog(#"%s: %#", __FUNCTION__, error);
In your connection:didReceiveResponse:, you really should look at the HTTP status code:
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200)
NSLog(#"%s: status code is %d; should be 200", __FUNCTION__, statusCode);
}
If it's not 200, you really want to know about that.
You report in one of your comments that you are seeing connectionDidFinishLoading: called, but never having didReceiveData called. That means (unsurprisingly) that there was no data received. So, you should:
Confirm that the connection:didReceiveResponse: reported a statusCode of 200; and
Confirm that the server code is working properly. I could imagine getting the behavior you describe if you had an error in your server PHP code (which is exacerbated by the fact that servers often have display_errors turned off in their php.ini file).
As an aside, if it's possible that the value associated with key1 might contain any reserved characters (as defined in section 2 of RFC 3986), you should percent-escape the string using CFURLCreateStringByAddingPercentEscapes. Thus:
NSString *post = [NSString stringWithFormat:#"key1=%#", [self percentEscapeString:vali]];
Where, per the W3C specs for application/x-www-form-urlencoded, you not only percent escape, but also replace spaces with + characters, thus:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}

Use:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Unless you have a compelling reason not to.
Example (probably non-working):
Note creating postData.
-(void)sendRequest {
NSString *vali = #"$uppl!3r$";
NSString *post = [NSString stringWithFormat:#"key1=%#",vali];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", [postData length]];
NSLog(#"%#", postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.ddemo3.enerjinet.com/webservices/ios/suppliers.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"data: %#", data);
}];
}
Oh, make life easier, use ARC.

Related

How do I Upload an Image to a Server through HTTP POST Request using FILES variable?

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

IOS HttpPost not working

I am trying to send multiple parameter for a registration usage. Here is my Code for Posting data :
-(void)PostRegistrationData:(NSString *)userEmail :(NSString *)Password{
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
/* We iterate the dictionary now
and append each pair to an array
formatted like <KEY>=<VALUE> */
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
}
/* We finally join the pairs of our array
using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:#"&"];
NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://teknofolk.com/spisrett_admin/slave/signup.php?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
NSMutableData *mutableData = [[NSMutableData alloc]init];
}
}
But no data i getting inserted . Am i missing something?
You have various choices what you want to use.
First option:
NSURLResponse *res = nil;
NSError *err = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];
(you have also the async way for this option).
or you can also follow your code and continue with this:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
and the request will be async and will call this methods (you need that this view controller responds to the NSURLConnectionDelegate and NSURLConnectionDataDelegate):
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
It was my mistake in the parameter.
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
Worked with simply this :
#"type":#"1",
#"request_type":#"2"
};
In my insertion i was passing wrong value on type and request type. Thanks to all for all

Why is didReceiveData function not working

I have a class which is used to get data from my server. The data returned from my server is in JSON. For some reason the didReceiveData won't run at all. I have placed NSLogs inside it to test it but it doesn't do anything?
Here is my code:
+(NSJSONSerialization *) getTask:(id)task_id{
NSString *post = [NSString stringWithFormat:#"&task_id=%#", task_id];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://my-server.com/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
NSLog(#"Testing");
}
return json;
}
// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"test");
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Thanks,
Peter
getTask: is a class method, which means the self is the class. Therefore the delegate methods must also be class methods.
But note that you cannot return the received JSON from the getTask: method, because NSURLConnection works asynchronously.
You need to start the connection. Try using the initWithRequest:delegate:startImmediately: method:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
or, just call the start method:
if(conn){
[conn start];
}

How to send big big string through NSURLConnection

This is my code.
- (void)loadData:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection found---------");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"reciving data---------");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"connection fail---------");
[self.pddelegate connectionError];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"data posting done---------");
[self.pddelegate dataPosted];
}
It is not working if url become bigger and give connection fail in logs.
Like
url=#".......order_details&admin=29&tableid=89&waiter_id=18&items=MzQ6MSwxMToxLDMzOjEsNjc6MSwzOToxLDY5OjEsNTY6MSw2ODoxLDg6MSw1NToxLDYyOjEsNzY6MSw0MToxLDIwOjEsNjE6MQ=="
see this SO post for get type request length What is the maximum length of a URL in different browsers?
for sending big string use POST type request instead of GET type.
We have there are two methods for sending data.
1. GET Method : Which is used for fixed length or limited length of string only.
2. POST Method : Which is used to send more string while comparing get method.
I have given the example Using PostMethod.
NSString *post =[[NSString alloc] initWithFormat:#"%#",YourString];
NSURL *url=[NSURL URLWithString:*#"YourURL like www.google.com"*];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
request.timeoutInterval = 60;
NSError *error = nil;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *errStr = _stringEmpty;
#try { errStr = [error localizedDescription]; }#catch (NSException * exception){ }
If any error occur errStr will show the error.
In the past, I have used some URL's that are around 2000 characters in length in iOS with no problem. NSURL, NSURLRequest, and NSURLConnection all managed just fine. If your URL is shorter than that, the problem is probably not due to its length, but instead related to the way the URL is constructed.

How to write http get and post in objective c?

I want to use http Get and Post for getting the request and response of certain URL request,
But i dont know how to use them in objective c..
and Which one will come first Get or Post in establishment of connection.?
how to modify the content and post them back to the server..
Can any one please help me?
for get use :
+(NSMutableURLRequest*)getURq_getansascreen:(NSString*)ws_name {
NSLog(#"%#",ws_name);
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ws_name] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[urlReq setHTTPMethod:#"GET"];
return urlReq;
}
for post use :
+(NSMutableURLRequest*)postURq_getansascreen:(NSString*)ws_name :(NSString*)service {
NSString *tempUrl = domainURL;
NSString *msgLength = [NSString stringWithFormat:#"%d",[ws_name length]];
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Service=%#",tempUrl,service]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlReq addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[urlReq setHTTPMethod:#"POST"];
[urlReq setHTTPBody: [ws_name dataUsingEncoding:NSUTF8StringEncoding]];
return urlReq;
}
//Call this in view did load as `
WSPContinuous *wspcontinuous = [[WSPContinuous alloc] initWithRequestForThread:[webService getURq_getansascreen:[webService GetDetails:str_filter]] sel:#selector(WS_GetDetailsLoaded:) andHandler:self];`
//create class WSPContinuous and add these fns..
-(id)initWithRequestForThread:(NSMutableURLRequest*)urlRequest sel:(SEL)seletor andHandler:(NSObject*)handler {
if (self=[super init]) {
self.MainHandler = handler;
self.targetSelector = seletor;
self.urlReq = urlRequest;
[self performSelectorOnMainThread:#selector(startParse) withObject:nil waitUntilDone:NO];
}
return (id)urlReq;
}
-(void)startParse{
NSLog(#"URL CALLING %#",urlReq.URL);
con = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (con) {
myWebData = [[NSMutableData data] retain];
NSLog(#"myWebData old....%#",myWebData);
}
else {
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
}
//-------------------------------connection-----------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[myWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[myWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *thexml = [[NSString alloc] initWithBytes:[myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
NSLog(#"xmlDictionary %#",thexml);
[thexml release];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:myWebData error:&parseError];
[AlertHandler hideAlert];
[MainHandler performSelector:targetSelector withObject:xmlDictionary];
}
If you want to start, a better idea would be to do some reading on NSMutableURLRequest and related topics like NSURLConnection.
You get sample code everywhere. Just google it.
Google search -> objective c get and post
and First hit -> Tutorials for using HTTP POST and GET on the iPhone in Objective-C

Resources