views:

5843

answers:

2

I am sending a post using NSURLRequest.

NSURL *url = [NSURL URLWithString:someUrlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]];

Within the body of the Request I am encoding the following NVP:

returnURL=http://someSite.com

The post is going through successfully, but I get an error back. The error states an invalid url.

So, I changed it to:

returnURL=http:%2F%2FsomeSite.com

With the same error.

I have also double checked it with Todd Ditchendorf's HTTP Client, with the same results.

I know I must be encoding this wrong can someone tell me what I am doing wrong?

Thanks Corey

*UPDATE: Thanks to those who answered. I missed an ampersand in my NVP values. So of course, as soon as I fixed it, everything was fine. What I suspectede, the encoding of a url in the body of the post was incorrect. I am not using the ASIHTTPRequest framework, but it did help me troubleshoot the problem (overkill for what I needed). *

+6  A: 

Consider using Ben Copsey's ASIHTTPRequest framework for generating and sending synchronous and asynchronous HTTTP requests (POST and GET):

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:@"http://someSite.com"] autorelease];
[request setPostValue:@"myValue1" forKey:@"myFormField1"];
[request setPostValue:@"myValue2" forKey:@"myFormField2"];
// etc.
[request start];
NSError *error = [request error];
if (!error)
  NSString *response = [request responseString];

His framework is a huge time-saver.

Alex Reynolds
ASIHttpRequest is freaking awesome!!
bentford
+2  A: 

I don't know if this solves your problem, but

[parameterString length]

is often not be equal to the length of

[parameterString dataUsingEncoding:NSUTF8StringEncoding]

because UTF8 encodes characters with varying numbers of bytes.

Chris Lundie