Monday, February 21, 2011

ASIHTTPRequest: Encoding in post data

I'm using ASIHTTPRequest to send a form this way:

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:foo forKey:@"post_var"];

How can I set the encoding of the nsstring foo??

The web receiving the form data expects the value in ISOLatin1

From stackoverflow
  • const char *_cFoo = "bar";
    NSString *_foo = [[NSString alloc] initWithCString:_cFoo encoding:NSISOLatin1StringEncoding];
    ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
    [request setPostValue:_foo forKey:@"post_var"];
    // ...
    [request trigger];
    [_foo release];
    

    EDIT: I'm not sure why the above wouldn't work. I guess I should try it out. But looking at the source for ASIHTTPRequest, the -setPostValue:forKey: method looks like it takes any NSObject subclass for a POST value:

    - (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
    {
       if (![self postData]) {
           [self setPostData:[NSMutableDictionary dictionary]];
       }
       [[self postData] setValue:[value description] forKey:key];
       [self setRequestMethod:@"POST"];
    }
    

    Perhaps convert an NSString to a C string and use its NSData representation as the POST variable value:

    NSString *_foo = @"bar";
    const char *_cFoo = [_foo cStringUsingEncoding:NSISOLatin1StringEncoding];
    NSData *_cFooData = [NSData dataWithBytes:_cFoo length:strlen(_cFoo)];
    [request setPostValue:_cFooData forKey:@"post_var"];
    
    Jorge : The point is I already have an UTF8 encoded NSString. Following your example: c_Foo = [foo UTF8String]; ...... It's not working. I dont get ISOLatin1 encoded strings :-(
    Jorge : Doing that, I get values like this: <6275656e f3212121 2121> in the form receiver.

0 comments:

Post a Comment