Sending a POST request from Cocoa to Tumblr

前端 未结 2 757
感情败类
感情败类 2020-12-01 05:15

This code snippet isn\'t working, I\'m getting an \"Authentication Failed.\" response from the server. Any ideas?

    NSMutableURLRequest *request = [[NSMuta         


        
相关标签:
2条回答
  • 2020-12-01 05:18

    As per the answers to this question, stringByAddingPercentEscapesUsingEncoding: doesn't perform a full escape encoding. For whatever reason, the CoreFoundation version of this method does, however:

    [(NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, 
        (CFStringRef)[[self mutableCopy] autorelease], NULL, 
        CFSTR("=,!$&'()*+;@?\n\"<>#\t :/"), kCFStringEncodingUTF8) autorelease];
    

    You can also use NSMutableString's replaceOccurencesOfString:withString:options: method to do the replacement manually, but that method is more repetitive and verbose. (See here.)

    0 讨论(0)
  • 2020-12-01 05:25

    The problem is that you are not creating a proper HTTP POST request. A POST request requires a properly formatted multipart MIME-encoded body containing all the parameters you want to send to the server. You are trying to set the parameters as HTTP headers which won't work at all.

    This code will do what you want, note especially the NSString categories that create a valid Multipart MIME string:

    @interface NSString (MIMEAdditions)
    + (NSString*)MIMEBoundary;
    + (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict;
    @end
    
    @implementation NSString (MIMEAdditions)
    //this returns a unique boundary which is used in constructing the multipart MIME body of the POST request
    + (NSString*)MIMEBoundary
    {
        static NSString* MIMEBoundary = nil;
        if(!MIMEBoundary)
            MIMEBoundary = [[NSString alloc] initWithFormat:@"----_=_YourAppNameNoSpaces_%@_=_----",[[NSProcessInfo processInfo] globallyUniqueString]];
        return MIMEBoundary;
    }
    //this create a correctly structured multipart MIME body for the POST request from a dictionary
    + (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict 
    {
        NSMutableString* result = [NSMutableString string];
        for (NSString* key in dict)
        {
            [result appendFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",[NSString MIMEBoundary],key,[dict objectForKey:key]];
        }
        [result appendFormat:@"\r\n--%@--\r\n",[NSString MIMEBoundary]];
        return result;
    }
    @end
    
    
    @implementation YourObject
    - (void)postToTumblr
    {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
                                        initWithURL:
                                        [NSURL URLWithString:@"http://www.tumblr.com/api/write"]];
        [request setHTTPMethod:@"POST"];
        //tell the server to expect 8-bit encoded content as we're sending UTF-8 data, 
        //and UTF-8 is an 8-bit encoding
        [request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
        //set the content-type header to multipart MIME
        [request addValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@",[NSString MIMEBoundary]] forHTTPHeaderField: @"Content-Type"];
    
        //create a dictionary for all the fields you want to send in the POST request
        NSDictionary* postData = [NSDictionary dictionaryWithObjectsAndKeys:
                                     _tumblrLogin, @"email",
                                     _tumblrPassword, @"password",
                                     @"regular", @"type",
                                     @"theTitle", @"title",
                                     @"theBody", @"body",
                                     nil];
        //set the body of the POST request to the multipart MIME encoded dictionary
        [request setHTTPBody: [[NSString multipartMIMEStringWithDictionary: postData] dataUsingEncoding: NSUTF8StringEncoding]];
        NSLog(@"Tumblr Login:%@\nTumblr Password:%@", _tumblrLogin, _tumblrPassword);
        [NSURLConnection connectionWithRequest:request delegate:self];
        [request release];
    }
    @end
    
    0 讨论(0)
提交回复
热议问题