Issuing a post request iPhone->Server from xcode - iphone

I've done many searches but none of the code fragments I find seem to work for me. I have the following fragment in xcode for running within my iPhone app:
NSURL *url = [NSURL URLWithString:#"http://blah.blah.com/rec.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSData *body = [#"data=crap" dataUsingEncoding:NSUTF8StringEncoding];
NSString *bodyLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:bodyLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:body];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
The rec.php is called fine but the post data does not make it through. The entry $_POST['data'] is empty. Could anyone let me know what I'm doing wrong?

Related

Objective-C equivalent of curl request

I'm trying to manipulate this curl request in Objective-C:
curl -u username:password "http://www.example.com/myapi/getdata"
I've implemented the following and I'm getting a data get error Domain=kCFErrorDomainCFNetwork Code=303 with NSErrorFailingURLKey=http://www.example.com/myapi/getdata:
// Make a call to the API to pull out the categories
NSURL *url = [NSURL URLWithString:#"http://www.example.com/myapi/getdata"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// Create the username:password string for the request
NSString *loginString = [NSString stringWithFormat:#"%#:%#", API_USERNAME, API_PASSWORD];
// Create the authorisation string from the username password string
NSData *postData = [loginString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I was hoping that someone could spot where I am going wrong with my attempt to manipulate the curl request and point me in the correct direction. Is there something obvious I'm missing out? The data returned from the API is in a JSON format.
I found that the best thing to do was to not attempt the authentication within the code and to put it straight in the URL itself. The working code looks as follows:
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"http://%#:%##www.example.com/myapi/getdata", API_USERNAME, API_PASSWORD]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This guide seems to do what you're looking for:
http://deusty.blogspot.co.uk/2006/11/sending-http-get-and-post-from-cocoa.html
Just as an FYI, a lot of classes accept initWithData, and NSData has a method dataWithContentsOfURL, if you want to avoid setting up NSURLConnections yourself this could be an easier way of achieving what you're looking for.

i want to send request by POST on iPhone,but the body can't be received by server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iPhone SDK Xcode 4.2 iOS 5- How do i send a json to url ? (POST not GET) [Resolved]
NSDictionary *requestDic=[NSDictionary dictionaryWithObjects:values forKeys:keys];
NSString *jsonreq=[requestDic JSONRepresentation];
NSURL *requrl=[NSURL URLWithString:[NSString stringWithFormat:#"%#index.php?r=%#&te=%#&noCheck=1&checkInstall=start",[Info serverUrl],[dictParameters objectForKey:#"r"],[dictParameters objectForKey:#"te"]]];
requrl = [NSURL URLWithString:[[requrl absoluteString] stringByAppendingString:subUrl]];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:requrl];
[req setHTTPMethod:#"POST"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json-x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *requestData=[NSData dataWithBytes:[jsonreq UTF8String] length:[jsonreq length]];
[req setHTTPBody:requestData];
[browser loadRequest:req]
Dilshand's answer is ok , but you can use ASIFormDataRequest for ease. like follow
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:mobileApplicationId forKey:#"mobileApplicationId"];
[request setPostValue:mobileApplicationVersion forKey:#"mobileApplicationVersion"];
[request setPostValue:userID forKey:#"userId"];
[request setPostValue:pass forKey:#"password"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
What you want to post server give complete detail and what error you are getting
try following i have done using this to send data to server and it works fine for me hope this helps
NSString *post =[[NSString alloc] initWithFormat:#"ProviderNPI=%#&PatientID=%#&FileURL=%#&FileTYPE=%#&DataSynID=%#& AppointmentListingsID=%#",providerNPI,patientID,FILEURL,FILETYPE,dataSynID,appointmentListingID];
NSURL *url=[NSURL URLWithString:#"http://myserver.com/Sync.php?"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[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];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
NSURL *url = [NSURL URLWithString:#"http://www.invoicera.com/app/api/check_json_api.php?token=7B92C122473A3D6F54E60D20AC5526D0"];
NSString *jsonRequest = [NSString stringWithFormat:#"&json_data=%#",[[NSString stringWithFormat:#"{\"listInvoice\":{\"client_id\":\"\",\"date_from\":\"\",\"date_to\":\"\",\"invoice_number\":\"\",\"invoice_record_status\":\"\",\"invoice_status\":\"\",\"page\":\"1\",\"per_page_record\":\"20\"}}"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",jsonRequest);
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSLog(#"%#",json_data);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: json_data];
NSLog(#"%#",json_data);
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [json_data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
// [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
// Successful connection.
if (nsUrlConnection) {
// [self initSpinner];
// [self spinBegin];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData=data;
[data release];
}
// Unsuccessful connection.
else {
}
// Clean up
[url release];
[request release];
// Close keypad.

how to POST comment to wordpress site

Encountered a problem on posting comment back to a comment box.
post not showing up, there is no error or whatsoever to check.
EDIT: Correct Answer
-(void)postToBoard
{
NSString *post = #"author=Jos&email=mail#domain.com.au&url=&comment=score+99.&submit=Post+Comment&comment_post_ID=1&comment_post_ID=1&comment_parent=0";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *URLString = #"http://site.com.au/?p=1";
NSURL *postURL = [NSURL URLWithString:URLString];
[request setURL:postURL];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"wp-comments-post.php" forHTTPHeaderField:#"HTTP/1.1"];
[request setHTTPBody:postData];
//self.receivedData = [NSMutableData data];
self.postConnection = [NSURLConnection connectionWithRequest:request delegate:self];
}
This line looks wrong:
[request setValue:#"wp-comments-post.php" forHTTPHeaderField:#"Content-Type"];
It should be:
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
I'm not sure what you're supposed to do with "wp-comments-post.php", should that perhaps be in the URL instead?

Cant Post To Server Well

i am trying to post to a server in the following code.
i cant receive the response that i need to get.
think i am making something wrong, need some help
NSString *uuid = #"acdede9b-6fa6-44d0-8837-cd11771139be";
NSString *rec = #"ewoJInNpZ25hdHVyZSIgPSAiQWphZElyM2hFclc2L0xReDYwNGtpZ3FpZmxZUll4MTdJUUN1VUQ3UG1LS2tCNU1yeUxvU2NOejdnKzVlYnZBS001TnV2R3dOVWRmcmFEeHN3eElONVJXZXFoc1Q0OEJMUVlXNzBnWmFyTUhVbW81SW1BdFVvZy9PWlQyTkVvdW5DNW5uR3JBQll0K0Q2VFdZK1hEL0NIczczcmpqcmtONnNFalNmR05kNEg4K0FBQURWekNDQTFNd2dnSTdvQU1DQVFJQ0NHVVVrVTNaV0FTMU1BMEdDU3FHU0liM0RRRUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2Y21sMGVURXpNREVHQTFVRUF3d3FRWEJ3YkdVZ2FWUjFibVZ6SUZOMGIzSmxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1CNFhEVEE1TURZeE5USXlNRFUxTmxvWERURTBNRFl4TkRJeU1EVTFObG93WkRFak1DRUdBMVVFQXd3YVVIVnlZMmhoYzJWU1pXTmxhWEIwUTJWeWRHbG1hV05oZEdVeEd6QVpCZ05WQkFzTUVrRndjR3hsSUdsVWRXNWxjeUJUZEc5eVpURVRNQkVHQTFVRUNnd0tRWEJ3YkdVZ1NX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lBOUlDSXhJanNLQ1NKd2RYSmphR0Z6WlMxa1lYUmxJaUE5SUNJeU1ERXhMVEV4TFRJNElEQXdPakUwT2pBd0lFVjBZeTlIVFZRaU93b0pJbWwwWlcwdGFXUWlJRDBnSWpRM05USXhNVFUzTlNJN0Nna2laWGh3YVhKbGN5MWtZWFJsTFdadmNtMWhkSFJsWkNJZ1BTQWlNakF4TVMweE1TMHlPQ0F3TVRveE5Eb3dNQ0JGZEdNdlIwMVVJanNLQ1NKbGVIQnBjbVZ6TFdSaGRHVWlJRDBnSWpFek1qSTBOREk0TkRBd01EQWlPd29KSW5CeWIyUjFZM1F0YVdRaUlEMGdJbU52YlM1aGJXOTBaV05vTGs5dVpWbGxZWElpT3dvSkluUnlZVzV6WVdOMGFXOXVMV2xrSWlBOUlDSXhNREF3TURBd01ERTBPRE00TURnMUlqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURFeExURXhMVEkzSURJeU9qRXpPak16SUVWMFl5OUhUVlFpT3dvSkltOXlhV2RwYm1Gc0xYUnlZVzV6WVdOMGFXOXVMV2xrSWlBOUlDSXhNREF3TURBd01ERTBPREk1TVRJeElqc0tDU0ppYVdRaUlEMGdJbU52YlM1aGJXOTBaV05vTG1Gd2NHTnBaR1Z1ZEVGd2NDSTdDZ2tpWW5aeWN5SWdQU0FpTVM0d0lqc0tmUT09IjsKCSJlbnZpcm9ubWVudCIgPSAiU2FuZGJveCI7CgkicG9kIiA9ICIxMDAiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==";
NSString *ServerContent = [NSString stringWithFormat:#"registerRecipt.aspx?udid=%#&receipt=%#",uuid,rec];
NSData *requestdata = [ServerContent dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"myserverurl"]];
request.timeoutInterval = 20;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestdata];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
error
The page cannot be displayed Open IIS Help, which is accessible in IIS Manager (inetmgr),
Try setting the Content-Length header:
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]]
forHTTPHeaderField:#"Content-Length"];

How to use .NET web service in iPhone, with POST method?

I am communicating with a .NET web service in an iPhone application, using the POST method, but I am not getting XML back as response. Here is my code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"Myserver/EventService.svc"]];
NSString *api = #"/registeruser";
NSData *body = [[NSString stringWithFormat:#"%#/%#/%#/%#/%#/%#/%#/%#/%#",
api, txtFName.text ,txtLName.text,
txtUName.text, txtEmail.text, txtPassword.text,
txtCity.text, txtState.text, str] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"url %#",url);
NSLog(#"body %#",[NSString stringWithFormat:#"%#/%#/%#/%#/%#/%#/%#/%#/%#",
api, txtFName.text, txtLName.text,
txtUName.text, txtEmail.text, txtPassword.text,
txtCity.text, txtState.text, str]);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPBody:body];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
NSLog(#"body len %d",[body length]);
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *XMLString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data %#",XMLString);
Please help me. Thanks in advance.
I have done that with following.
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"Myserver/EventService.svc/webservice/%#/%#",para1,para2]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:0 forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *XMLString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data %#",XMLString);
Have you tried something smaller first? Say doing an http post locally? Or doing an http post to that server with a simple html form?
I have run into this issue myself and decided to step back and start with a simple http post to make sure my objective-c was correct first.
I used this tutorial to get me started -hope it helps